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)
这道题,我不会输出路径,好伤心啊,后来在网上看的别人的代码的思路,自己打出来了
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
int a1[6][6];
int vis[6][6];
struct node
{
int x;
int y;
int step;
int num[50];
};
node ans;
int i,j,len;
int dis[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int x1=0;
int y1=0;
node bfs()
{
memset(vis,0,sizeof(vis));
queue<node>q;
node a,b;
a.x=0;
a.y=0;
a.step=0;
vis[0][0]=1;
q.push(a);
while(!q.empty())
{
a=q.front();
q.pop();
if(a.x==4&&a.y==4)
{
// len=a.step;
//prinf(a);
return a;
}
for(i=0;i<4;i++)
{
b=a;
b.x=a.x+dis[i][0];
b.y=a.y+dis[i][1];
if(vis[b.x][b.y]||a1[b.x][b.y]==1)
continue;
if(b.x>=0&&b.x<5&&b.y>=0&&b.y<5)
{
vis[b.x][b.y]=1;
b.step=a.step+1;
b.num[a.step]=i;
q.push(b);
}
}
}
return a;
}
void prinf(node w)
{
for(i=0;i<=w.step;i++)
{
printf("(%d, %d)\n",x1,y1);
if(i!=w.step)
{
x1+=dis[w.num[i]][0];
y1+=dis[w.num[i]][1];
}
}
}
int main()
{
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&a1[i][j]);
}
}
ans=bfs();
prinf(ans);
return 0;
}