题解:在dfs()之前先判断终点和起点是否存在0,起点和终点是否为同一个数字进行预判断,递归函数加两个参数,一个方向,一个转弯次数,在递归时如果方向改变,次数加一,否则不变。
#include <stdio.h>
#include <string.h>
const int N = 1005;
int row, col, m[N][N], que, x2, y2, flag, vis[N][N];
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
void dfs(int x, int y, int face, int cnt) {
if (cnt > 2)
return;
if (x == x2 && y == y2) {
flag = 1;
return;
}
for (int i = 0; i < 4; i++) {
int x1 = x + dx[i];
int y1 = y + dy[i];
if (x1 < 0 || x1 >= row || y1 < 0 || y1 >= col)
continue;
if (!vis[x1][y1] && (m[x1][y1] == 0 || (x1 == x2 && y1 == y2))) {
vis[x1][y1] = 1;
if (i != face)
dfs(x1, y1, i, cnt + 1);
else
dfs(x1, y1, i, cnt);
if (flag)
return;
vis[x1][y1] = 0;
}
}
}
int main() {
while (scanf("%d%d", &row, &col) && (row + col)) {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
scanf("%d", &m[i][j]);
scanf("%d", &que);
while (que--) {
flag = 0;
memset(vis, 0, sizeof(vis));
int x1, y1;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
if (m[x1 - 1][y1 - 1] != m[x2 - 1][y2 - 1]) {
printf("NO\n");
continue;
}
if (m[x1 - 1][y1 - 1] == 0 || m[x2 - 1][y2 - 1] == 0) {
printf("NO\n");
continue;
}
x2--;
y2--;
x1--;
y1--;
for (int i = 0; i < 4; i++) {
int x0 = x1 + dx[i];
int y0 = y1 + dy[i];
if (x0 < 0 || x0 >= row || y0 < 0 || y0 >= col)
continue;
if (!vis[x0][y0] && (m[x0][y0] == 0 || (x0 == x2 && y0 == y2))) {
vis[x0][y0] = 1;
dfs(x0, y0, i, 0);
if (flag)
break;
vis[x0][y0] = 0;
}
}
if (flag)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}