K - 迷宫问题

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

InputcopyOutputcopy
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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值