🍑 算法题解专栏
🍑 saber --> 搜索 --> DFS之连通性模型 --> 迷宫
输入
2
3
.##
..#
#..
0 0 2 2
5
.....
###.#
..#..
###..
...#.
0 0 4 0
输出
YES
NO
import java.util.*;
class Main
{
static int N = 110;
static int n, ha, la, hb, lb;
static boolean[][] st = new boolean[N][N];
static char[][] g = new char[N][N];
static int[] dx = { -1, 1, 0, 0 };
static int[] dy = { 0, 0, -1, 1 };
static boolean dfs(int x, int y)
{
if (x == hb && y == lb)// 递归出口
return true;
if (g[x][y] == '#')// 一进来就得判断是否为墙,因为起点可能就是墙
return false;
st[x][y] = true;// 标记已遍历
for (int i = 0; i < 4; i++)// 枚举四个方向
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || xx >= n || yy < 0 || yy >= n)// 非法越界,跳过
continue;
if (st[xx][yy])// 已遍历,跳过
continue;
if (g[xx][yy] == '#')// 走不通,跳过
continue;
if (dfs(xx, yy))
return true;
}
return false;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while (T-- > 0)
{
for (int i = 0; i < N; i++)
Arrays.fill(st[i], false);
n = sc.nextInt();
for (int i = 0; i < n; i++)
{
String s = sc.next();
for (int j = 0; j < n; j++)
{
g[i][j] = s.charAt(j);
}
}
ha = sc.nextInt();
la = sc.nextInt();
hb = sc.nextInt();
lb = sc.nextInt();
if (dfs(ha, la))
System.out.println("YES");
else
System.out.println("NO");
}
}
}