DSF之迷宫问题

在这里插入图片描述

#include<iostream>
#include<cstdio>

using namespace std;

const int MAX = 101;
char map[MAX][MAX];
bool lib[MAX][MAX]; //标记该点是否已经来过
int DicX[4] = {
    
    0, 1, 0, -1}; //向东南西北四个方向移动,x坐标相当于行坐标
int DicY[4] = {
    
    1, 0, -1, 0}; //向东南西北四个方向移动,y坐标相当于列坐标
int n, x0, y0, x1, y1;

bool DFS(int x, int y);

int main()
{
    
    
	int k;
	cin >> k;
	while (k-- > 0)
	{
    
    
		cin >> n;
		for (int i=0; i<n; i++)
		{
    
    
			for (int j=0; j<n; j++)
			{
    
    
				cin >> map[i][j];
				lib[i][j] = 0;//初始化
			}
		}
		cin >> x0 >> y0 >> x1 >> y1;

		if (map[x0][y0]=='#' || map[x0][y0]=='#')//果起点或者终点有一个不能通行(为#),则看成无法办到。
		{
    
    
			cout << "NO" << endl;
			continue;
		}

		lib[x0][y0] = 1;//标记为旧点
		if (DFS(x0, y0))
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}

    return 0;
}

bool DFS(int x, int y) //x和y分别表示当前行坐标和列坐标,找到终点,返回真
{
    
    
	if (x == x1 && y == y1)//到达目标点
	{
    
    
		return true;
	}

	int nx, ny;
	bool flag = false;
	for (int i=0; i<4; i++)
	{
    
    
		nx = x + DicX[i];
	    ny = y + DicY[i];
		if (nx >= 0 && nx < n && ny >= 0 && ny < n && !lib[nx][ny] && map[nx][ny] == '.')
		{
    
    //符合条件的点
			lib[nx][ny] = 1; //走过了就不能再来
			flag = DFS(nx, ny);//开始遍历
		}

		if (flag) //找到终点,返回真
			return true;
	}
	return false;}

猜你喜欢

转载自blog.csdn.net/wuyvle/article/details/113552520
DSF