回溯法题型1 迷宫找路

Tom is addicted to a game recently, but he often comes across all kinds of mazes in playing the game, among which there are both passable mazes and unpassable mazes. 

Tom is too lazy. He wants you to write a program to help him solve all the mazes once and for all. 

 

 

输入

The first line enters a positive integer n, representing the number of mazes to be solved.

After that, n groups of data are input into each group with a number m, which represents the length and width of the maze.

Then input m rows, m columns of a matrix, where 0 represents the grid obstacles, can not pass, 1 represents can pass.

The data ensures that the cells at the top left and bottom right are not obstructed.

The maze is no bigger than 30x30.
 

 

输出

Determine whether each maze can go from the beginning of the upper left corner to the end of the lower right corner.
 Output "YES" or "NO" to each maze to indicate whether the maze can be traversed.

 

样例输入

2
3
1 1 0
0 1 1
0 0 1
4
1 1 0 1
0 0 1 1
1 1 0 1
1 1 0 1

 

样例输出

YES
NO

#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set> 
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 100
 
int a[N][N], b[N][N];
int T, n;
int c[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
int flag;
 
void Find(int x, int y);
int main ()
{
    cin >> T;
    while (T--)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        flag = 0;
        cin >> n;
        for(int i=1; i<=n; i++)
            for(int j=1; j<=n; j++)
                cin >> a[i][j];
        b[1][1]=1;
        Find(1,1);
        if(flag)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    return 0;
}
 
void Find(int x, int y)
{
    int i;
    if(x==n && y==n)
    {
        flag =1;
        return;
    }
    for( i=0; i<4; i++)
    {
        int tx = x + c[i][0], ty = y + c[i][1];
        if(!b[tx][ty] && a[tx][ty] && tx<=n && tx>=1 && ty<=n && ty>=1)
        {
            b[tx][ty]=1;
            Find(tx,ty);
            b[tx][ty]=0;//重点:发现到不了终点再折回来重新换一条路
        }
    }
    return;
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值