题目来源
题目描述
题目解析
#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;
}