Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 8 Accepted Submission(s) : 2
Problem 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 <iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
int map[5][5],ce[10][10],b[2][4]={-1,1,0,0,0,0,-1,1};///控制所走的方向
struct node {
int x,y,cout;
}z[100];
void print(int i)///打印路径
{
int q=z[i].cout;
if(q==-1)
{
cout<<"(0, 0)"<<endl;
return ;
}
print(q);
cout<<"("<<z[i].x<<", "<<z[i].y<<")"<<endl;
}
void bfs(int x,int y)
{
memset(ce,0,sizeof(ce));
int head=0;
int tail=0;
z[tail].x=x;
z[tail].y=y;
z[tail].cout=-1;
ce[x][y]=1;
tail++;
while(tail>head)
{
int m=z[head].x;
int n=z[head].y;
if(m==4&&n==4)
{
print(head);
return ;
}
for(int i=0;i<4;i++)
{
int px=m+b[0][i];
int py=n+b[1][i];
if(px<0||px>4||py<0||py>4||map[px][py]==1||ce[px][py]==1)
{
continue;
}
z[tail].x=px;
z[tail].y=py;
z[tail].cout=head;///记录是哪一个的点走到现在的点方便打印路径
tail++;
ce[px][py]=1;
}
head++;
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
{
cin>>map[i][j];
}
bfs(0,0);
}