#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;
}
迷宮
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.