1.完成了一道bfs相关的题目
#include <stdio.h>
#include <string.h>
typedef struct note//构造结构体
{
int x;
int y;
int step;
}p;
p que[1000000];
char a[1000][1000];
int nextx[4] = { 0,0,1,-1 };//给出可能走的方式
int book[1000][1000];
int nexty[4] = { 1,-1,0,0 };
int head, tail,n;
void bfs(int x1, int y1, int x2, int y2)
{
int tx, ty;
head = 1, tail = 1;
que[tail].x = x1;
que[tail].y = y1;
que[tail].step = 0;
tail++;
book[x1][y1] = 1;
while (head < tail)
{
for (int i = 0; i < 4; i++)
{
tx = que[head].x + nextx[i];
ty = que[head].y + nexty[i];
if (tx<1 || ty<1 || tx>n || ty>n) continue;
if (a[tx][ty] == '0' && book[tx][ty] == 0)
{
book[tx][ty] = 1;
que[tail].x = tx;
que[tail].y = ty;
que[tail].step = que[head].step + 1;
tail++;
}
if (tx == x2 && ty == y2)//判断是否走到了终点
{
return;
}
}
head++;
}
}
int main()
{
int x1,x2,y1,y2;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%s", a[i]+1);
}
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
bfs(x1, y1, x2, y2);
printf("%d",que[tail - 1].step);//输出结果
return 0;
}
在编写代码的过程中,遇到了几个问题:
1.无论如何更改,结果都为WA
原因:输入时,数字间应无间隙
改正方法:
将输入时的数组由整型更改为字符
2.一直在比较step结果,导致越来越乱与复杂
改正方法:
通过查阅资料,可知通过bfs,其第一次到达的路径就是最短的
原因:bfs是按照从起始节点开始的距离逐步向外搜索的。它以起始节点为中心,像水波一样一层一层地向外扩展搜索范围。在每一层的搜索过程中,所有与当前层节点直接相邻的节点都被探索到。
假设起始节点为S,目标节点为T。当BFS第一次到达T时,所经过的边数就是从S到T的最短路径长度。因为bfs是按照距离分层搜索的,如果有更短的路径,那么在之前的层就会已经探索到目标节点了。
例如,把搜索空间想象成一个网格,从左上角的起始点找右下角的目标点。bfs会先搜索起始点周围一圈的点(距离为1),然后再搜索距离为2的圈,以此类推。一旦找到目标点,这个路径就是在这种逐步扩散的搜索方式下的最短距离,不用再去比较其他路径长度。
24.2吴晓娴
2024.12.20