#include <bits/stdc++.h>using namespace std;
int n;
int m;
char a[100][100];
int g = 0;
void dfs(int x, int y) {
if(a[x][y]=='#' or x>n or y>m or x<=0 or y<=0){
return;
}
if(g==1){
return ;
}
if (x == n && y == m) {
g = 1;
return ;
}
a[x][y] = '#';
dfs(x, y + 1);
dfs(x + 1, y);
dfs(x, y - 1);
dfs(x - 1, y);
}
int main() {
cin >> n;
cin >> m;
for (int j = 1; j <= n; j++) {
for (int h = 1; h <= m; h++) {
cin >> a[j][h];
}
}
dfs(1, 1);
if (g == 0) {
cout << "NO";
} else {
cout << "YES";
}
return 0;
}
P2199 最后的迷宫
C++
#include <bits/stdc++.h>using namespace std;
const int N = 2e4 + 10;
int n, m, sx, sy, ex, ey;
char mp[N];
bool vis[N];
struct node {
int x, y, step;
};
queue<node>q;
const int dx[] = {1, 1, -1, 1, 0, -1, 0, -1};
const int dy[] = {0, 1, 0, -1, 1, 1, -1, -1};
bool check(int x, int y) {
if (x < 1 || x > n || y < 1 || y > m || mp[(x - 1)*m + y] == 'X') {
return 0;
} else return 1;
}
bool look(int stx, int sty) {
for (int i = 0; i < 8; ++i) {
int xx = dx[i] + stx;
int yy = dy[i] + sty;
while (check(xx, yy)) {
if (xx == ex && yy == ey)return 1;
xx += dx[i];
yy += dy[i];
}
}
return 0;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j)cin >> mp[(i - 1)*m + j];
}
while (1) {
scanf("%d%d%d%d", &ex, &ey, &sx, &sy);
if (sx == sy && sy == ex && ey == ex && ex == 0)return 0;
while (q.size())q.pop();
memset(vis, 0, sizeof vis);
q.push({sx, sy, 0});
vis[(sx - 1)*m + sy] = 1;
bool flag = 1;
while (q.size()) {
node now = q.front();
q.pop();
if (now.x == ex && now.y == ey || look(now.x, now.y)) {
printf("%d\n", now.step);
flag = 0;
break;
}
for (int i = 0; i < 8; i += 2) {
int xx = now.x + dx[i];
int yy = now.y + dy[i];
if (!check(xx, yy) || vis[(xx - 1)*m + yy])continue;
q.push({xx, yy, now.step + 1});
vis[(xx - 1)*m + yy] = 1;
}
}
if (flag)printf("Poor Harry\n");
}
return 0;
}