我之前学习广度优先搜索有些感触,现在书写代码(这是一道最短路径求步数题)如果要写出路径,不可以用此方法,如果实验只进行一次,可将a[50][50]和book[50][50]合并处理
习惯把验证过程不删方便以后观看
#include <stdio.h>
//广度优先搜索
struct note {
int x;
int y;
};
int main() {
struct note que[2][100];
int a[50][50] = {0};
int book[50][50] = {0};
int n, m, tail, i, k, sx, sy, tx, ty, p, q, f, h, ste,e,w;
f = 0;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++) {
for (k = 0; k < m; k++) {
scanf("%d", &a[i][k]);
}
}
scanf("%d %d %d %d", &sx, &sy, &p, &q);
int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
ste = 0;
tail = 0;
que[0][tail].x = sx;
que[0][tail].y = sy;
book[sx-1][sy-1] = 1;
h=1;
while (1) {
ste++;
for (k = 0; k < h; k++) {
for (i = 0; i < 4; i++) {
tx = que[(ste - 1) % 2][k].x + d[i][0];
ty = que[(ste - 1) % 2][k].y + d[i][1];
if (sy < 1 || sx < 1 || sx > n || sy > m) {
continue;
}
if (a[tx - 1][ty - 1] == 0 && book[tx - 1][ty - 1] == 0) {
book[tx - 1][ty - 1] = ste;
que[ste % 2][tail].x = tx;
que[ste % 2][tail].y = ty;
tail++;
//printf("%d ", ste);
}
if (tx == p && ty == q) {
printf("%d", ste);
f = 1;
break;
}
}
if (f == 1) {
// printf("来了");
break;
}
}
/*
printf("\n");
for(w=0;w<n;w++){
for(e=0;e<m;e++){
printf("%d ",book[w][e]);
}
printf("\n");
}
printf("%d\n",tail);
h = tail;
tail=0;
*/
if (f == 1) {
// printf("来啦");
break;
}
}
getchar();
getchar();
return 0;
}