迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11603 | Accepted: 6946 |
Description
定义一个二维数组:
int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, };
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
要在BFS的基础上多建一个数组~~记录它的前一个~~
AC-code:
#include<cstdio>
#include<cstring>
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int vis[10][10],map[10][10],pre[30];
struct node
{
int x,y;
}a[30];
int can(int x,int y)
{
if(!vis[x][y]&&x>=0&&y>=0&&x<5&&y<5&&map[x][y]==0)
return 1;
return 0;
}
void print(int x)
{
int t=pre[x];
if(t==0)
{
printf("(0, 0)\n");
printf("(%d, %d)\n",a[x].x,a[x].y);
return ;
}
else
print(t);
printf("(%d, %d)\n",a[x].x,a[x].y);
}
void bfs()
{
int head=0;
int tail=1;
memset(vis,0,sizeof(vis));
a[head].x=0;
a[head].y=0;
pre[0]=-1;
while(head<tail)
{
int x=a[head].x;
int y=a[head].y;
if(x==4&&y==4)
{
print(head);
return ;
}
for(int i=0;i<4;i++)
{
int xx=x+dx[i];
int yy=y+dy[i];
if(can(xx,yy))
{
vis[xx][yy]=1;
a[tail].x=xx;
a[tail].y=yy;
pre[tail]=head;
tail++;
}
}
head++;
}
return ;
}
int main()
{
int i,j;
for(i=0;i<5;i++)
for(j=0;j<5;j++)
{
scanf("%d",&map[i][j]);
}
bfs();
return 0;
}