定义一个二维数组:
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)
据说测试数据很水的一道题,用dfs写错了交上去居然还过了。
用bfs找最短路,用递归输出路径。
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<queue>
#include<algorithm>
using namespace std;
int mp[5][5];//存图
bool vis[5][5];
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
typedef struct node
{
int x,y;
}no;
node r[5][5];//定义一个二维的结构体
int check(int x,int y)//检查
{
if(x>=0&&x<5&&y>=0&&y<5&&vis[x][y]==false&&mp[x][y]==0)
return 1;
else
return 0;
}
void pri(int x1,int y1)//递归打印
{
if(x1==0&&y1==0)
{
printf("(0, 0)\n");
return;
}
pri(r[x1][y1].x,r[x1][y1].y);
printf("(%d, %d)\n",x1,y1);
}
int main()
{
int x1,y1;
memset(mp,0,sizeof(mp));
memset(vis,false,sizeof(vis));
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>mp[i][j];
node now;//当前位置
node next;//下一位置
queue<node> q;
now.x=0,now.y=0;
q.push(now);
vis[0][0]=true;
while(!q.empty())//bfs
{
now=q.front();
q.pop();
if(now.x==4&&now.y==4)//最快找到终点的那条一定是最短路
break;
for(int i=0;i<4;i++)
{
x1=now.x+dir[i][0];
y1=now.y+dir[i][1];
if(check(x1,y1))
{
next.x=x1,next.y=y1;
vis[x1][y1]=true;
q.push(next);
r[x1][y1].x=now.x;//重点!通过二维结构体记录父子节点关系
r[x1][y1].y=now.y;
}
}
}
pri(4,4);
//system("pause");
return 0;
}