题目描述
-
定义一个二维数组:
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 Sample
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
Output Sample
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)
AC代码
#include<bits/stdc++.h>
#define ts ios::sync_with_stdio (false);cin.tie(0);
using namespace std;
#define INF 99999999
#define endl '\n'
#define MOD 1000000007
#define PI acos(-1)
#define YES cout<<"YES"<<endl
#define NO cout<<"NO"<<endl
typedef long long ll;
struct p
{
int x,y;
int step;
pair<int,int> path[30];
}s,e;
int mp[6][6];
int vis[10][10];
int dir[][2]={
{-1,0},{1,0},{0,-1},{0,1}
};
bool check(int x,int y)
{
if(x<0||x>=5||y<0||y>=5)
return true;
if(mp[x][y]==1||vis[x][y])
return true;
return false;
}
void bfs()
{
queue<p> que;
que. push(s);
s.step=0;s.path[s.step]=pair<int,int>(0,0);
vis[s.x][s.y]=1;
while(!que.empty())
{
p head=que.front();
que.pop();
if(head.x==e.x&&head.y==e.y)
{
for(int i=0;i<=head.step;i++)
cout << '(' << head.path[i].first << ", " << head.path[i].second << ')' << endl;
return;
}
for(int i=0;i<4;i++)
{
int nx=head.x+dir[i][0];
int ny=head.y+dir[i][1];
if(check(nx,ny)) continue;
vis[nx][ny]=1;
p tt=head;
tt.x=nx;tt.y=ny;tt.step=head.step+1;tt.path[tt.step]=pair<int,int>(nx,ny);
que. push(tt);
}
}
}
void solve()
{
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
cin>>mp[i][j];
}
}
s.x=s.y=0;
e.x=e.y=4;
bfs();
}
int main()
{
ll t=1;
while(t--)
solve();
return 0;
}
/*
___________ __ .__ .__
_ _____// |_| |__ ___________ ____ _____ | |
| __)_\ __\ | _/ __ _ __ _/ __ \__ \ | |
| | | | Y \ ___/| | /\ ___/ / __ | |__
/_______ /|__| |___| /___ >__| ___ >____ /____/___________
/ / / / / /_____/_____/
*/
//2022.7.27