定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
一个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)
题意:
相信题目已经表述得很清楚了,因为又是求最优解,所以还是要用到广度搜索。
注意:
1.在解决这个问题的过程中,出现了一个问题。题目中已经说明0是可以走的,而1才是不可以走的。我却习惯性的认为,0是不可以走,1可走,导致浪费了很多的是时间。(所以,请以后看准题目要求)
2.学到两个小点:
2.1 最开始自己写的时候,并没有定义成结构体,只是单纯的设置了两个变量去表示横坐标和纵坐标,传入的时候也是bfs(0,0)。后来就有点麻烦,定义队列的时候也不好定义。所以以后遇到多变量(大于一个就算哦)就定义成结构体,这样反方便处理。
2.2vis[][]数组的作用:v[][]==0就表示向上移动,v[][]==1就表示向下移动,v[][]==2就表示向右移动,v[][]==3就表示向做移动,它标记的是移动过后的一个点,而我们的输出函数像是递归调用,正好相反的一个过程。以v[x][y]==1为例,等于1说明向下移动了,所以你要输出out(x,y+1);(你向下走了一步,理所当然以前的位置需要加回去)。
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int maze[10][10];
int vis[10][10];
int flag,cnt;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
typedef struct node
{
int x;
int y;
}node;
bool judge(node x)
{
//cout<<"进入到judge()函数"<<endl;
if(x.x<0||x.x>4||x.y<0||x.y>4||maze[x.x][x.y]!=0)
return false;
if(vis[x.x][x.y]!=-1)
return false;
return true;
}
void out(int x,int y)
{
//cout<<"进入到out()函数"<<endl;
if(x==0&&y==0)
{
printf("(%d, %d)\n",0,0);
return ;
}
else if(vis[x][y]==0) out(x,y-1);
else if(vis[x][y]==1) out(x,y+1);
else if(vis[x][y]==2) out(x-1,y);
if(vis[x][y]==3) out(x+1,y);
printf("(%d, %d)\n",x,y);
}
void bfs()
{
queue<node>q;
node first;
node second;
first.x=0;
first.y=0;
q.push(first);
while(!q.empty())
{
first=q.front();
q.pop();
if(first.x==4&&first.y==4)
{
//cout<<"进入到bfs()函数"<<endl;
out(4,4);
return ;
}
for(int i=0;i<4;i++)
{
second.x=first.x+dir[i][0];
second.y=first.y+dir[i][1];
if(judge(second))
{
vis[second.x][second.y]=i;
q.push(second);
}
}
}
}
int main()
{
for(int i=0;i<5;i++)
for(int j=0;j<5;j++)
cin>>maze[i][j];
memset(vis,-1,sizeof(vis));
bfs();
return 0;
}