迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 9112 | Accepted: 5392 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
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)
Source
ac代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<string>
#include<iostream>
#define INF 0xfffffff
using namespace std;
int map[20][20],ansx[20],ansy[20];
int minn=INF;
int dx[4]={0,1,-1,0};
int dy[4]={1,0,0,-1};
struct s
{
int x,y,step;
}a,temp,ans,pre[20][20];
int jud(struct s a)
{
if(a.x<0||a.x>=5||a.y<0||a.y>=5)
return 0;
if(map[a.x][a.y])
return 0;
return 1;
}
void bfs()
{
queue<struct s >q;
a.x=0;
a.y=0;
a.step=0;
q.push(a);
map[0][0]=1;
while(!q.empty())
{
a=q.front();
q.pop();
temp=a;
for(int i=0;i<4;i++)
{
temp.x=a.x+dx[i];
temp.y=a.y+dy[i];
temp.step=a.step+1;
if(jud(temp))
{
if(temp.x==4&&temp.y==4)
{
if(temp.step<minn)
{
minn=temp.step;
pre[4][4].x=a.x;
pre[4][4].y=a.y;
}
continue;
}
map[temp.x][temp.y]=1;
pre[temp.x][temp.y].x=a.x;
pre[temp.x][temp.y].y=a.y;
q.push(temp);
}
}
}
}
int main()
{
int i,j;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
scanf("%d",&map[i][j]);
}
bfs();
int x,y,k=0;
x=y=4;
while(1)
{
int tx,ty;
tx=x;
ty=y;
if(!pre[x][y].x&&!pre[x][y].y)
break;
ansx[k]=pre[tx][ty].x;
ansy[k++]=pre[tx][ty].y;
x=pre[tx][ty].x;
y=pre[tx][ty].y;
}
printf("(0, 0)\n");
for(i=k-1;i>=0;i--)
{
printf("(%d, %d)\n",ansx[i],ansy[i]);
}
printf("(4, 4)\n");
}