K - 迷宫问题
定义一个二维数组:
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) |
Sponsor
最短路径用bfs来求就可以了,难点在于把最短路径输出出来,这就需要dfs的回溯过程。用bfs找到最短路径之后,v数组存放的这个路径中每一个点的前一个点的坐标,这样方便回溯的时候,把各个点输出,这样dfs和bfs结合,利用bfs来把最优的路径找到,利用dfs的回溯把最优的路径输出
/*Where there is light, in my heart.*/
/*SUMMER_TRAINING DAY 24*/
#include <bits/stdc++.h>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
//
#define IOS ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//#define INF 0x3f3f3f
#define ll long long
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
#define unmap(a,b) unordered_map<a,b>
#define unset(a) unordered_set<a>
#define F first
#define S second·
#define pb push_back
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
#define _rep(i, a, b) for (int i = (a); i >= (b); --i)
#define mode 1e4+7
#define pi acos(-1)
typedef double db;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef vector<int> vi;
const int N = 2e5+5;
//
struct node{
int x;
int y;
}v[15][15];
int mp[15][15],vis[15][15],step[15][15];
int dir[4][2]={0,1,1,0,0,-1,-1,0};
queue <node> q;
//
void dfs(int x,int y){
if(x==0&&y==0) return ;
dfs(v[x][y].x,v[x][y].y);
printf("(%d, %d)\n",v[x][y].x,v[x][y].y);
}
//
void bfs(int a,int b){
node last,now;
last.x=a;
last.y=b;
q.push(last);
while(!q.empty()){
last=q.front();
q.pop();
if(last.x==4&&last.y==4){
dfs(last.x,last.y);
printf("(%d, %d)\n",last.x,last.y);
return ;
}
for(int i=0;i<4;i++){
now.x=last.x+dir[i][0];
now.y=last.y+dir[i][1];
if(now.x>=0&&now.x<=5&&now.y>=0&&now.y<=5&&mp[now.x][now.y]!=1&&vis[now.x][now.y]==0){
v[now.x][now.y].x=last.x;
v[now.x][now.y].y=last.y;
vis[now.x][now.y]=1;
q.push(now);
}
}
}
}
//
signed main(){
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
cin>>mp[i][j];
}
}
bfs(0,0);
}
//made by shun 20220727