#include<iostream>
#include<stack>
using namespace std;
#pragma warning(disable:4996)
const int N = 5;
//从文本中读取迷宫存入数组
template<class T>
void InitMaze(T** arr)
{
FILE* f = fopen("maze.txt", "r");
if (f == NULL)
{
cout << "open maze fail" << endl;
return;
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
int ch = fgetc(f);
if (ch == ' ' || ch == '\n')
{
j -= 1;
}
else
{
arr[i][j] = ch - '0';
continue;
}
}
}
fclose(f);
}
struct Step //当前位置信息
{
int _row; //行
int _col; //列
};
template<class T>
bool Maze(T** arr, int EntranceRow, int EntranceCol)
{
Step step;
stack<Step> s;
step._row = EntranceRow;
step._col = EntranceCol;
if (s.empty())
{
arr[EntranceRow][EntranceCol] = 2; //将走过的位置赋值为2
s.push(step); //将入口信息插入栈中
}
while (step._row < N - 1)
{
//向上走
step._row -= 1;
if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty())
{
if (arr[step._row][step._col] == 0)
{
arr[step._row][step._col] = 2;
s.push(step);
continue;
}
}
//向右走
step._row += 1; //恢复行数
step._col += 1;
if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty())
{
if (arr[step._row][step._col] == 0)
{
arr[step._row][step._col] = 2;
s.push(step);
continue;
}
}
//向下走
step._col -= 1; //恢复列数
step._row += 1;
if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty())
{
if (arr[step._row][step._col] == 0)
{
arr[step._row][step._col] = 2;
s.push(step);
continue;
}
}
//向左走
step._row -= 1; //恢复行数
step._col -= 1;
if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty())
{
if (arr[step._row][step._col] == 0)
{
arr[step._row][step._col] = 2;
s.push(step);
continue;
}
}
if (!s.empty())
{
step = s.top();
arr[step._row][step._col] = 3; //讲行不通的位置赋值为3
s.pop();
step = s.top(); //取出栈顶元素
continue;
}
else
{
return false;
}
}
return true;
}
template<class T>
void Print(T** arr)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
int main()
{
//动态开辟二维数组
int** arr = new int*[N];
for (int i = 0; i < N; i++)
{
arr[i] = new int[N];
}
InitMaze<int>(arr);
Maze(arr,1,0);
Print<int>(arr);
for (int i = 0; i < N; i++) //释放二维数组
{
delete[] arr[i];
arr[i] = NULL;
}
delete[] arr;
arr = NULL;
getchar();
return 0;
}
迷宫
最新推荐文章于 2022-01-20 19:40:02 发布