题目描述
给定起点和终点,问是否有这样一条路能够连通。
输入格式
输出格式
数据范围
1 ≤ n ≤ 100 1≤n≤100 1≤n≤100
输入样例
2
3
.##
..#
#..
0 0 2 2
5
.....
###.#
..#..
###..
...#.
0 0 4 0
输出样例
YES
NO
算法
这题就是典型的连通性问题,属于模板题,注意起点和终点可能不合法
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
char mat[N][N];
bool st[N][N];
int n;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool dfs(int sx, int sy, int ex, int ey) { // 从sx,sy能否走到ex,ey
if (sx == ex && sy == ey) {
return true;
}
st[sx][sy] = true;
for(int i = 0; i < 4; ++ i) {
int xx = sx + dx[i], yy = sy + dy[i];
if (0 <= xx && xx < n && 0 <= yy && yy < n && !st[xx][yy] && mat[xx][yy] == '.') {
if (dfs(xx, yy, ex, ey)) {
return true;
}
}
}
//注意这里没有 st[sx][sy] = false !
return false;
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
for (int i = 0; i < n; ++ i)
scanf("%s", &mat[i]);
int sx, sy, ex, ey;
scanf("%d%d%d%d", &sx, &sy, &ex, &ey);
memset(st, false, sizeof st);
if (mat[sx][sy] == '#' || mat[ex][ey] == '#') {
cout << "NO" << endl;
continue;
}
if (dfs(sx, sy, ex, ey)) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}