营救公主,在如下迷宫(图)中搜索寻找公主,每次在一个时间单位t内,只能走一步,问能否在规定的时间T内救出公主。
。 。 。 。
。 。 。 。
。 。 。 。
S * * P
其中S代码开始寻找的起始位置,P代表公主的位置," 。"表示可以自由通过的位置, “ * ”表示不能通过的位置。
分析: 图的广度优先搜索算法 -- 要用队列来存储遍历,此处可以用数组来代替队列queue
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE 20
typedef struct {
int x;
int y;
int time;
}st_pos;
static int dir[][2] = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
/*
广度优先搜索,用一个固定长度的数组实现队列的功能
*/
static int bfs(char *visited, st_pos start_pos, st_pos end_pos, int n, int m)
{
int i = 0;
int queue_length = 0;
int queue_point_pos = 0;
st_pos temp1_pos;
st_pos temp2_pos;
st_pos queue_pos[MAXSIZE * MAXSIZE];
memset(&temp1_pos, 0, sizeof(st_pos));
memset(&temp2_pos, 0, sizeof(st_pos));
memset(queue_pos, 0, MAXSIZE * MAXSIZE *sizeof(st_pos));
//加入队列
queue_pos[0].x = start_pos.x;
queue_pos[0].y = start_pos.y;
queue_length++;
while (queue_point_pos < queue_length)
{
//出队
temp1_pos.x = queue_pos[queue_point_pos].x;
temp1_pos.y = queue_pos[queue_point_pos].y;
temp1_pos.time = queue_pos[queue_point_pos].time;
queue_point_pos++;
if (temp1_pos.x == end_pos.x && temp1_pos.y == end_pos.y)
return temp1_pos.time; //找到了终点,返回所用时间,与已知剩余时间作对比
for (i = 0; i < 4; i++) //以此点temp1_pos为中心,上下左右四个方向移动一个位置
{
temp2_pos.x = temp1_pos.x + dir[i][0];
temp2_pos.y = temp1_pos.y + dir[i][1];
temp2_pos.time = temp1_pos.time;
if (temp2_pos.x >= 0 && temp2_pos.x < m && temp2_pos.y >= 0 && temp2_pos.y < n
&& visited[temp2_pos.x * n + temp2_pos.y] != '*'
&& visited[temp2_pos.x * n + temp2_pos.y] != 'S')
{
visited[temp2_pos.x * n + temp2_pos.y] = '*'; //表示这个位置走过了,不要重复了
temp2_pos.time++; //每走一格时间耗费加1
queue_pos[queue_length].x = temp2_pos.x;
queue_pos[queue_length].y = temp2_pos.y;
queue_pos[queue_length].time = temp2_pos.time;
queue_length++;
}
}
}
return -1;
}
int main()
{
char map[4][4] = { { '.', '.', '.', '.' }, { '.', '.', '.', '.' }, { '.', '.', '.', '.' }, { 'S', '*', '*', 'P' } };
int m = 4;
int n = 4;
int t = 10;
char *p = &map[0][0];
st_pos start_pos;
st_pos end_pos;
int i = 0;
int j = 0;
memset(&start_pos, 0, sizeof(st_pos));
memset(&end_pos, 0, sizeof(st_pos));
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
if (map[i][j] == 'S')
{
start_pos.x = i;
start_pos.y = j;
}
if (map[i][j] == 'P')
{
end_pos.x = i;
end_pos.y = j;
}
}
}
printf("(%d,%d)-->(%d,%d)\n", start_pos.x, start_pos.y, end_pos.x, end_pos.y);
int ret = bfs(p, start_pos, end_pos, n, m);
printf("%d\n", ret);
if (ret == -1 || ret > t)
printf("NO\n");
else
printf("yes\n");
system("pause");
return 0;
}