走出迷宫可以使用递归或者栈的方式,这里采用的是栈的方法,迷宫的矩阵如图,1是墙壁,0是路
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
0 0 0 1 1 1 1 1 1 1
1 1 0 1 1 1 1 1 1 1
1 1 0 1 0 0 0 1 1 1
1 1 0 0 0 1 1 1 1 1
1 0 0 1 0 1 1 1 1 1
1 0 1 1 0 0 0 1 1 1
1 0 0 1 1 1 0 1 1 1
1 1 0 1 1 1 1 1 1 1
#include<iostream>
#include<stack>
using namespace std;
const int n = 10;
int maze[n][n] = {0};
struct Pos
{
int _row;
int _col;
};
stack<Pos> minStack;//记录最优路径
void InitMaze(int maze[][n], int size)
{
FILE* fOut = fopen("map.txt", "r");
if(fOut == NULL)
{
cout<<"Open Maze.txt Fail"<<endl;
exit(-1);
}
for (int i=0; i<size; ++i)
{
for(int j=0; j<size;)
{
char ch = fgetc(fOut);
if (ch == EOF)
{
cout<<"Maze Map Error!"<<endl;
exit(-1);
}
if (ch == '1' || ch == '0')
{
maze[i][j] = ch - '0';
++j;
}
}
}
fclose(fOut);
}
int** f(int n)
{
int** f = new int*[n];
for (int i=0; i<n; i++)
{
f[i] = new int[n];
}
return f;
}
void PrintMaze(int maze[][n], int size)
{
for(int i=0; i<size; i++)
{
for (int j=0; j<size; j++)
{
cout<<maze[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
void PrintMinMaze(int maze[][n], int size, stack<Pos> minStack)
{
while (!minStack.empty())
{
Pos cur = minStack.top();
maze[cur._row][cur._col] = 0;
minStack.pop();
}
for(int i=0; i<size; i++)
{
for (int j=0; j<size; j++)
{
cout<<maze[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
bool CheckIsAccess(int maze[][n], Pos cur)
{
if (cur._row>=0 && cur._row <n
&& cur._col>=0 && cur._col<n
&& maze[cur._row][cur._col] == 0)
return true;
return false;
}
bool GetMazePath(int maze[][n], Pos entry, stack<Pos>& paths)
{
bool isMinPaths = false;
paths.push(entry);
maze[entry._row][entry._col] = 2;
while (!paths.empty())
{
Pos cur = paths.top();
Pos next = cur;
if ((cur._row == n-1 || cur._col == n-1
|| cur._col == 0 || cur._row == 0)
&&(cur._col!=entry._col || cur._row!=entry._row))
{
isMinPaths = true;
if(minStack.size()==0 || minStack.size()>paths.size())
minStack = paths;
}
//向左
next._col -=1;
if(CheckIsAccess(maze, next))
{
paths.push(next);
maze[next._row][next._col] = 2;
continue;
}
//向上
next = cur;
next._row -=1;
if(CheckIsAccess(maze, next))
{
paths.push(next);
maze[next._row][next._col] = 2;
continue;
}
//向右
next = cur;
next._col +=1;
if(CheckIsAccess(maze, next))
{
paths.push(next);
maze[next._row][next._col] = 2;
continue;
}
//向下
next = cur;
next._row +=1;
if(CheckIsAccess(maze, next))
{
paths.push(next);
maze[next._row][next._col] = 2;
continue;
}
//出栈,进行回溯
Pos temp = paths.top();
maze[temp._row][temp._col] = 3;//将可以走但是不通的置为3
paths.pop();
}
return isMinPaths;
}
测试代码
#include "Maze.h"
int main()
{
int mazeArray[n][n] = {0};
InitMaze(mazeArray, n);
PrintMaze(mazeArray, n);
stack<Pos> paths;
Pos entry = {2,0};
bool ret = GetMazePath(mazeArray, entry, paths);
if (ret)
{
cout<<"成功走出迷宫"<<endl;
PrintMaze(mazeArray, n);
cout<<"最优路径:"<<endl;
PrintMinMaze(mazeArray, n, minStack);
}
}