定义一个二维数组:
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
Inputcopy | Outputcopy |
---|---|
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 |
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4) |
#include<iostream>
#include<queue>
typedef long long ll;
#define endl '\n'
#define buff ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr);
using namespace std;
int ans=-1;
int mp[10][10];
int vis[10][10];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
struct mmp
{
int x,y,step;
}; mmp a; mmp b;mmp from[100];
queue<mmp> q;
int main()
{
ios::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
for(int i=0;i<=4;i++)
{
for(int j=0;j<=4;j++) cin>>mp[i][j];
}
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)
{
ans=a.step;
from[a.step].x=4,from[a.step].y=4;
break;
}
for(int i=0;i<=3;i++)
{
int xx=a.x+dir[i][0];
int yy=a.y+dir[i][1];
if(xx>=0&&xx<=4&&yy>=0&&yy<=4&&vis[xx][yy]==0&&mp[xx][yy]==0)
{
vis[xx][yy]=1;
b.x=xx,b.y=yy,b.step=a.step+1;
from[a.step].x=a.x,from[a.step].y=a.y;
q.push(b);
}
}
}
for(int i=0;i<=ans;i++)
{
cout<<"("<<from[i].x<<", "<<from[i].y<<")"<<'\n';
}
}