解题思路:很明显,这是一道最最基础的广度优先搜索,废话不多说,上代码
注意事项:注意“size = q.size()"
参考代码:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct node
{
int x, y;
}t;
queue <node> q;
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
int main()
{
bool a[105][105];
int T;
scanf("%d", &T);
for (int i = 1; i <= T; i++){
int m, n;
scanf("%d%d", &m, &n);
memset(a, 0, sizeof(a));
int x0, y0, x1, y1;
char temp;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++){
cin >> temp;
if (temp == 'S') x0 = i, y0 = j;
if (temp == 'E') x1 = i, y1 = j;
if (temp == '#') a[i][j] = 1;
}
int s = 0;
bool b = 1;
a[x0][y0] = 1;
q.push(node({x0, y0}));
while (!q.empty() && b){
s++;
int size = q.size();
for (int i = 1; i <= size; i++){
t = q.front();
q.pop();
for (int j = 0; j < 4; j++){
int x = t.x + dx[j], y = t.y + dy[j];
if (x >= 1 && x <= m && y >= 1 && y <= n && a[x][y] == 0){
a[x][y] = 1;
if (x == x1 && y == y1) b = 0;
else q.push(node({x, y}));
}
}
}
}
if (!b) printf("%d\n", s);
else printf("-1\n");
}
return 0;
}
0.0分
1 人评分