C++实现迷宫问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现迷宫问题相关的知识,希望对你有一定的参考价值。
#include <iostream>
using namespace std;
#include <stack>
#include <assert.h>
//初始化迷宫
void InitMaze(int* maze,int row, int col)
{
FILE* fout = fopen("Maze.txt", "r");
assert(fout);
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col;)
{
char ch = fgetc(fout);
if (ch == EOF)
{
cout<<"Init MazeMap fail"<<endl;
exit(false);
}
if (ch == ‘1‘ || ch == ‘0‘)
{
maze[i * row + j] = ch - ‘0‘;
++j;
}
}
}
fclose(fout);
}
struct Pos
{
int _row; //行
int _col; //列
};
//打印迷宫
void PrintMaze(int* maze, int row, int col)
{
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
cout<<maze[i * row + j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
//判断当前位置是否为0
inline bool CheckIsAccess(int* maze, int row, int col, Pos pos)
{
if (pos._row < row && pos._col < col
&& maze[pos._row * col + pos._col] == 0)
{
return true;
}
return false;
}
//判断迷宫是否有出口
bool GetMazePath(int* maze, int row, int col, Pos entry, stack<Pos>& path)
{
assert(maze);
path.push(entry);
maze[entry._row * col + entry._col] = 2;//将走过的路标记为2
while (!path.empty())
{
Pos cur = path.top();
Pos next = cur;
if (row-1 == next._row)//找到出口
{
return true;
}
//判断右边是否为0
next = cur;
next._col++;
if (CheckIsAccess(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//上
next = cur;
next._row--;
if (CheckIsAccess(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//下
next = cur;
next._row++;
if (CheckIsAccess(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
//左
next = cur;
next._col--;
if (CheckIsAccess(maze, row, col, next))
{
maze[next._row * row + next._col] = 2;
path.push(next);
continue;
}
path.pop();//四个方向都不通,返回上一步
}
return false;//栈为空,没有找到出口
}
void TestMaze()
{
int maze[10][10] = {};
Pos entry = {1, 0};
stack<Pos> path;//将走过的路径保存在栈path中
InitMaze((int*)maze, 10, 10);
PrintMaze((int*)maze, 10, 10);
GetMazePath((int*)maze, 10, 10, entry, path);
PrintMaze((int*)maze, 10, 10);
}
int main()
{
TestMaze();
return 0;
}
本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1775724
以上是关于C++实现迷宫问题的主要内容,如果未能解决你的问题,请参考以下文章