解救小哈
小哈在一个(m * n)大小的迷宫(0 ⇐ m, n ⇐ 50)里迷路了。在迷宫中,每个单元格要么是空地,要么是障碍物。现在要找到从起点到小哈位置的最短步数。
思路:
使用队列储存扩展,扩展时每发现一个点就将这个点储存到队列中。当一个点扩展完毕,将其出队。
源码:
#include<stdio.h>
struct queue {
int x;
int y;
int s;
};
int main() {
struct queue que[2500];
int tx, ty;
int next[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
int a[51][51];
int book[51][51] = {0};
int m, n;
int q, p;
int i, j;
int flag = 0;
int head = 0;
int tail = 0;
int k;
//初始化队列
que[tail].x = 1;
que[tail].y = 1;
que[tail].s = 0;
tail++;
book[1][1] = 1;
printf("请输入地图大小:");
scanf("%d %d", &n, &m);
printf("请输入地图:\n");
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
}
}
printf("请输入起点:");
scanf("%d %d", &que[head].x, &que[head].y);
printf("请输入终点:");
scanf("%d %d", &q, &p);
while (head < tail) {
for (k = 0; k < 4; k++) {
// 寻找下一步
tx = que[head].x + next[k][0];
ty = que[head].y + next[k][1];
if (tx < 1 || tx > n || ty < 1 || ty > m) { //判断出界
continue;
}
if (a[tx][ty] == 1 || book[tx][ty] == 1) { //判断是否是障碍物或已走过
continue;
}
que[tail].x = tx; //入队
que[tail].y = ty;
que[tail].s = que[head].s + 1;
tail++;
book[tx][ty] = 1;
if (tx == q && ty == p) { //判断是否到达终点
flag = 1;
break;
}
}
if (flag == 1) {
break;
}
head++;
}
printf("最短步数:%d\n", que[tail - 1].s);
return 0;
}