定义一个二维数组:
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>
using namespace std;
struct node
{
int x,y;
int xx[100];
int yy[100];
int t;
};
int vis[10][10];
int nex[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int a[10][10] = {
{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}
};
queue<node> q;
void bfs()
{
node q1,q2;
q1.x=0;q1.y=0;
q1.t=0;
q1.xx[0]=0;q1.yy[0]=0;
q.push(q1);
while(!q.empty())
{
q1=q.front();
q.pop();
if(q1.x==4 && q1.y==4)
{
for(int i=0;i<=q1.t;i++)
printf("(%d, %d)\n",q1.xx[i],q1.yy[i]);
return;
}
for(int i=0;i<4;i++)
{
int xx=q1.x+nex[i][0];
int yy=q1.y+nex[i][1];
if(a[xx][yy] || xx<0 || xx>=5 || yy<0 || yy>=5 || vis[xx][yy])
continue;
q2=q1;
q2.t++;
q2.x=xx;q2.y=yy;
vis[xx][yy]=1;
q2.xx[q2.t]=xx;q2.yy[q2.t]=yy;
q.push(q2);
}
}
}
int main()
{
vis[0][0]=1;
bfs();
return 0;
}
方法二:跟一个很厉害的北大的大佬(ACWing的创始人)学的,从终点开始搜一遍,记录一下终点可达的点,以及路径长度。再正着遍历一下,输出最短的路径。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int mp[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,
};
int n=5,m=5;
int nex[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int dis[10][10];
void bfs()
{
queue<pair<int,int> >q;
memset(dis,-1,sizeof(dis));
pair<int,int> q1;
dis[n-1][m-1]=0;
q.push({n-1,m-1});
while(!q.empty())
{
q1=q.front();
q.pop();
int x=q1.first,y=q1.second;
if(x==0 && y==0)
break;
for(int i=0;i<4;i++)
{
int xx=x+nex[i][0];
int yy=y+nex[i][1];
if(xx<0 || xx>=n || yy<0 || yy>=m || mp[xx][yy] || dis[xx][yy]!=-1)
continue;
dis[xx][yy]=dis[x][y]+1;
q.push({xx,yy});
}
}
}
int main()
{
bfs();
int x=0,y=0;
printf("(%d,%d)\n",x,y);
while(x!=n-1 || y!=m-1)
{
for(int i=0;i<4;i++)
{
int xx=x+nex[i][0];
int yy=y+nex[i][1];
if(xx<0 || xx>=n || yy<0 || yy>=m || mp[xx][yy])
continue;
if(dis[xx][yy]+1==dis[x][y])
{
x=xx;y=yy;
printf("(%d,%d)\n",x,y);
break;
}
}
}
return 0;
}