走迷宫大致有两种
1. 设置used数组,走之前判断,走到结点标记这个结点为已使用。但是别回溯,这样之后还要判断这个点
2. 设置地图,走一次就+1,适合带环迷宫求最短路
普通迷宫模板
typedef struct Pos {
int x;
int y;
Pos(int a, int b)
:x(a), y(b)
{
}
}Pos;
int PassMaze(vector<vector<int> >& maze, const Pos& entry, const Pos& cur, vector<Pos>& path, vector<Pos>& min) {
if (maze[cur.x][cur.y] != 1) {
return 0;
}
if ((cur.x == 0 || cur.y == 0 || cur.x == maze.size() - 1 || cur.y == maze[0].size() - 1)
&& !(cur.x == entry.x && cur.y == entry.y))
{
path.push_back(cur);
return 1;
}
path.push_back(cur);
maze[cur.x][cur.y] += 1;
int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
for (int i = 0; i < 4; i++) {
int x = cur.x + dir[i][0];
int y = cur.y + dir[i][1];
Pos next(x, y);
if (PassMaze(maze, entry, next, path, min)) {
return 1;
}
}
//回溯条件
path.pop_back();
//不要回溯标记 maze[cur.x][cur.y] = 1;
return 0;
}
int main() {
vector<vector<int> > maze = {
{ 0,0,0,0,0,0 },
{ 0,1,0,1,1,0 },
{ 0,1,1,1,1,0 },
{ 0,1,0,0,1,1 },
{ 0,1,1,1,1,0 },
{ 0,1,0,0,0,0 },
};
vector<Pos> path;
PassMaze(maze, Pos(5, 1), Pos(5, 1), path, min);
}
求最短路
要点:
- 在向下层递归前,检查边界合法,检查下一个结点值是不是大于当前值+1,若是则需要更新,或者==1是第一次走
- 走失败了,不需要回溯结点值。因为结点值可以作为判断合法条件
- 找到一个路径后,更新最小栈,pop当前栈
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef struct Pos {
int x;
int y;
Pos(int a, int b)
:x(a), y(b)
{
}
}Pos;
bool valid(vector<vector<int> >& maze, Pos& next) {
if (next.x < 0 || next.y < 0 || next.x >= maze.size() || next.y >= maze[0].size()) {
return false;
}
return true;
}
void update(vector<Pos>& path, vector<Pos>& min) {
if (min.empty() || path.size() < min.size()) {
min.clear();
for (int i = 0; i < path.size(); ++i) {
min.push_back(path[i]);
}
}
}
void PassMaze(vector<vector<int> >& maze, const Pos& entry, const Pos& cur, vector<Pos>& path, vector<Pos>& min) {
if ((cur.x == 0 || cur.y == 0 || cur.x == maze.size() - 1 || cur.y == maze[0].size() - 1)
&& !(cur.x == entry.x && cur.y == entry.y))
{
path.push_back(cur);
update(path, min);
path.pop_back();
return;
}
path.push_back(cur);
int dir[4][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
for (int i = 0; i < 4; i++) {
int x = cur.x + dir[i][0];
int y = cur.y + dir[i][1];
Pos next(x, y);
if (valid(maze, next) &&( maze[next.x][next.y] > 1+ maze[cur.x][cur.y] || maze[next.x][next.y] == 1)){
maze[next.x][next.y] = maze[cur.x][cur.y] + 1;
PassMaze(maze, entry, next, path, min);
}
}
path.pop_back();
return ;
}
int main() {
vector<vector<int> > maze = {
{ 0,0,0,0,0,0 },
{ 0,1,0,1,1,0 },
{ 0,1,1,1,1,0 },
{ 0,1,0,0,1,1 },
{ 0,1,1,1,1,0 },
{ 0,1,0,0,0,0 },
};
//栈保存当前路径,最小路径
vector<Pos> path;
vector<Pos> min;
PassMaze(maze, Pos(5, 1), Pos(5, 1), path, min);
for (int i = 0; i < maze.size(); i++) {
for (int j = 0; j < maze[0].size(); j++) {
cout << maze[i][j] << " ";
}
cout << endl;
}
}