回溯法题型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 30×30.
 

 

输出

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;
}
 

 

    原文作者:回溯法
    原文地址: https://blog.csdn.net/qq_43475252/article/details/84995385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞