华为机试:迷宫问题

题目来源

题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

题目解析

#include <utility>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <functional>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <map>
#include <random>
#include <ctime>
#include <iterator>

using namespace std;

class Solution{
    struct Info{
        int len;
        std::string path;
        Info(int len, int x, int y) : len(len){
            path = "(" + to_string(x) + "," + to_string(y) + ")";
        }

        Info(int len, std::string Path) : len(len){
            path = std::move(Path);
        }
    };

    std::map<std::string, Info *> cache;
public:
    // 最短路径
    Info* dfs(std::vector<std::vector<int>> &m, int i, int j){
        // 不能走
        if(i < 0 || j < 0 || i == m.size() || j == m[0].size() || m[i][j] == 1){
            return new Info(INT_MAX, "");
        }

        // 当前路可以走
        std::string currPath = "(" + to_string(i) + "," + to_string(j) + ")";

        // 之前走过的路
        if(cache.count(currPath)){
            return cache[currPath];
        }
        
        
        // 是否到达了终点
        if(i == m.size() - 1 && j == m[0].size() - 1){
            return  cache[currPath] = new Info(0, currPath);
        }

     
        // 没有到达终点就开始往四个方向探索
        m[i][j] = 1;  //先标记下当前路已经走过了
        // 接下来往上下左右四个方向探索
        auto p1 = dfs(m, i - 1, j);
        auto p2 = dfs(m, i + 1, j);
        auto p3 = dfs(m, i, j - 1);
        auto p4 = dfs(m, i, j + 1);

        // 数据保证有唯一解
        int nextLen = std::min(std::min(p1->len, p2->len), std::min(p3->len, p4->len));
        std::string nextPath;
        if(nextLen == p1->len){
            nextPath = p1->path;
        } if(nextLen == p2->len){
            nextPath = p2->path;
        }else if(nextLen == p3->len){
            nextPath = p3->path;
        }else{
            nextPath = p4->path;
        }

		// 当前位置可能是陷阱,到达不了终点!!!!!
        nextLen = nextLen == INT_MAX ? nextLen : nextLen + 1;
        std::string realPath = nextLen == INT_MAX ? "" : currPath  + "\n" + nextPath;
        return cache[currPath] = new Info(nextLen, realPath);
    }
};



int main(){
    std::vector<std::vector<int>> m
         {{0, 1, 0, 0, 0},
          {0, 1, 1, 1, 0},
          {0, 0, 0, 0, 0},
          {0, 1, 1, 1, 0},
          {0, 0, 0, 1, 0}};

    Solution a;
    auto ans = a.dfs(m, 0, 0);

    std::cout <<  ans->path ;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值