文章目录
Coronavirus
题解
用数字代替字符,用二维数组存储地图,可以走的路用0表示。
在搜索之前对高位地段进行处理,九个格子全部表示为1。
BFS。
注意不要忘记标记遍历过的点。
AC代码
#include <bits/stdc++.h>
#define IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define mms(x, n) memset(x, n, sizeof(x))
#define INF (0x3f3f3f3f)
using namespace std;
const int N = 51;
int n, m;
int maze[N][N];
int sx, sy, ex, ey;
int d[N][N];
int v[N][N];
int f[4][2] = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1}
};
int ff[8][2] = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1},
{-1, -1},
{-1, 1},
{1, -1},
{1, 1}
};
void init(int x, int y) {
for (int i = 0; i < 7; i++) {
int xx = x + ff[i][0], yy = y + ff[i][1];
if (xx < 0 || xx > n || yy < 0 || yy > m) continue;
maze[xx][yy] = 1;
}
}
typedef pair<int, int> P;
int main() {
IO;
cin >> n >> m;
mms(d, -1);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
char c;
cin >> c;
if (c == '*') {
init(i, j);
} else if (c == 'S') {
sx = i, sy = j;
} else if (c == 'E') {
ex = i, ey = j;
}
}
}
queue<P> q;
q.push(make_pair(sx, sy));
d[sx][sy] = 0;
v[sx][sy] = 1;
while (!q.empty()) {
P p = q.front();
q.pop();
int x = p.first, y = p.second;
if (x == ex && y == ey) break;
for (auto & i : f) {
int xx = x + i[0], yy = y + i[1];
if (xx < 0 || xx > n || yy < 0 || yy > m|| maze[xx][yy]==1 || v[xx][yy]==1) continue;
v[xx][yy] = 1;
q.push(make_pair(xx,yy));
d[xx][yy] = d[x][y] + 1;
}
}
int ans = d[ex][ey];
if (ans==-1)cout << "Impossible";
else cout << ans;
return 0;
}