题目来源:http://poj.org/problem?id=3984
题目大意:给你一个5*5的迷宫,让你从左上角走到右下角,求最短路径,并将路径输出。
源代码:
/**********************************
**********广度优先搜索************
***********************************/
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define N 5
int maze[N][N];//maze用来记录迷宫的形状
int visited[N][N];//flag用来记录该点有没有走过
int dir[4][2] = { 0,1,1,0,0,-1,-1,0};
struct pos{
int x;
int y;
int pre;
}que[100];//用一个队列来存储路径
void print( int head)
{
if( que[head].pre != -1)
{
print(que[head].pre);
printf("(%d, %d)\n",que[head].x,que[head].y);
}
}
void bfs( int x, int y)
{
int head = 0;//队头
int tail = 0;//队尾
//将当前x、y入队
que[head].x = x;
que[head].y = y;
que[head].pre = -1;
visited[x][y] = 1;
//队尾++
tail++;
int tx;
int ty;
while( head < tail)
{
for( int i = 0; i < 4; i++)
{
tx = que[head].x+dir[i][0];//分别向上下左右四个方向搜索
ty = que[head].y+dir[i][1];
//判断有没有出界
if( tx < 0 || tx > N-1 || ty < 0 || ty > N-1)
continue;
//如果有路并且没有走过
if( maze[tx][ty] == 0 && visited[tx][ty] == 0)
{
visited[tx][ty] = 1;//走这个点
que[tail].x = tx;//将tx、ty入队
que[tail].y = ty;
que[tail].pre = head;//从head拓展出来的
tail++;
}
if( tx == 4 && ty == 4)
{
print(head);
return;
}
}
head++;//当前head指向的拓展完之后往后走
}
}
int main()
{
memset(visited,0,sizeof(visited));//初始化
for( int i = 0; i < N; i++)
for( int j = 0; j < N; j++)
scanf("%d",&maze[i][j]);
printf("(0, 0)\n");
bfs(0,0);
printf("(4, 4)\n");
return 0;
}