poj 3984 迷宫问题
2012-04-13 17:04 璋廊 阅读(198) 评论(0) 收藏 举报定义一个二维数组:
它表示一个迷宫,其中的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)
#include<stdio.h>
struct point
{
int x,y;
int fx,fy;//用来记录上一步走的位置;
}s[100];//用数组模拟队列;
int a[10][10];
int dir[4][2]={1,0,-1,0,0,-1,0,1};//方向数组;
int DFS()
{
point cut,next;
cut.x=cut.y=cut.fx=cut.fy=0;
int head=0,top=1,i;
s[head]=cut;
while(1)
{
cut=s[head++];
next.fx=cut.x;
next.fy=cut.y;
for(i=0;i<4;i++)
{
next.x=cut.x+dir[i][1];
next.y=cut.y+dir[i][0];
if(next.x>=0&&next.y>=0&&next.fy<5&&next.y<5)
{
if(a[next.x][next.y]==0)
s[top++]=next;
if(next.x==4&&next.y==4)
{
s[top++]=next;
return top;
}
}
}
}
}
int main()
{
int i,j,sx,sy,h;
int b[101],c[101];
for(i=0;i<5;i++)
for(j=0;j<5;j++)
scanf("%d",&a[i][j]);
int k=DFS();
b[0]=4;//记录最短步数;
c[0]=4;
sx=s[k-1].fx;sy=s[k-1].fy;
h=1;
for(i=k-2;i>=0;i--)
{
if(sx==s[i].x&&s[i].y==sy)
{
b[h]=sx;c[h++]=sy;
sx=s[i].fx;
sy=s[i].fy;
}
}
for(i=h-1;i>=0;i--)
{
printf("(%d, %d)\n",b[i],c[i]);
}
return 0;
}
浙公网安备 33010602011771号