解题思路:很明显,这是一道最最基础的广度优先搜索,废话不多说,上代码
注意事项:注意“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 人评分
字符串的输入输出处理 (C语言代码)浏览:711 |
C语言程序设计教程(第三版)课后习题7.5 (C语言代码)浏览:590 |
大神老白 (C语言代码)浏览:695 |
C二级辅导-进制转换 (C语言代码)浏览:658 |
WU-小九九 (C++代码)浏览:1713 |
C语言考试练习题_保留字母 (C语言代码)浏览:743 |
求圆的面积 (C语言代码)浏览:1756 |
幸运数 (C++代码)浏览:1309 |
C语言程序设计教程(第三版)课后习题9.10 (C语言代码)浏览:866 |
C语言训练-亲密数 (C语言描述,反正怎么都能对)浏览:2256 |