迷宫问题

#include <bits/stdc++.h>

using namespace std;

/*迷宫的起点和终点坐标*/

const int StartX = 0,StartY = 0;

const int EndX = 4,EndY = 4;

const int M = 5,N = 5;

/*迷宫矩阵,0代表通路,1代表障碍*/

vector< vector<int> > maze = {{0,0,0,0,0},

  {0,1,0,1,0},

  {0,1,0,0,0},

  {0,1,0,1,1},

  {0,0,0,0,0}};

pair<int,int> GetNextDirection(int x,int y,vector< vector<bool> > &mark){

/*up*/

if(x-1 >= 0 && mark[x-1][y] == false && maze[x-1][y] == 0)

return pair<int,int>(x-1,y);

/*right*/

if(y+1 < N && mark[x][y+1] == false && maze[x][y+1] == 0)

return pair<int,int>(x,y+1);

/*down*/

if(x+1 < M && mark[x+1][y] == false && maze[x+1][y] == 0)

return pair<int,int>(x+1,y);

/*left*/

if(y-1 >= 0 && mark[x][y-1] == false && maze[x][y-1] == 0)

return pair<int,int>(x,y-1);

return pair<int,int>(-1,-1);

}

/*找迷宫路径,找到一条路径即可*/

void Maze_FindOnePath(int x,int y,stack<pair<int,int>> &path){

/*标记每个点是否被走过,单独设置标记数组是为了不修改maze数组*/

vector< vector<bool> >mark(M,vector<bool>(N,false));

path.push(pair<int,int>(x,y));

mark[x][y] = true;

/*栈不为空且栈顶元素不是结束位置*/

while(path.empty() == false && ( path.top().first != EndX || path.top().second != EndY)){

/*从上下左右四个方向中随便找一个可走的方向*/

pair<int,int> nextPos = GetNextDirection(path.top().first,path.top().second,mark);

if(nextPos.first == -1 && nextPos.second == -1){

/*回溯*/

path.pop();

continue;

}

path.push(nextPos);

mark[nextPos.first][nextPos.second] = true;

}

}

/*深度搜索找迷宫所有路径*/

void Maze_FindAllPath(int x,int y,stack<pair<int,int>> &cur,vector< stack<pair<int,int>> > &ret){

cur.push(pair<int,int>(x,y));

maze[x][y] = -1;

if(x == EndX && y == EndY){

ret.push_back(cur);

maze[x][y] = 0;

}

if(x-1>=0 && maze[x-1][y] == 0)

Maze_FindAllPath(x-1,y,cur,ret);

if(x+1 < M && maze[x+1][y] == 0)

Maze_FindAllPath(x+1,y,cur,ret);

if(y-1>=0 && maze[x][y-1] == 0)

Maze_FindAllPath(x,y-1,cur,ret);

if(y+1 < N && maze[x][y+1] == 0)

Maze_FindAllPath(x,y+1,cur,ret);

cur.pop();

maze[x][y] = 0;

}

int main(){

stack<pair<int,int>> path;

Maze_FindOnePath(0,0,path);

while(path.empty() == false){

cout<<path.top().first<<","<<path.top().second<<endl;

path.pop();

}

/*

stack<pair<int,int>> curPath;

vector< stack<pair<int,int>> > allPath;

Maze_FindAllPath(StartX,StartY,curPath,allPath);

for(auto i = 0;i < allPath.size();++i){

cout<<"Next Path:"<<endl;

while(!allPath[i].empty()){

cout<<allPath[i].top().first<<","<<allPath[i].top().second<<endl;

allPath[i].pop();

}

}*/

return 0;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容