您的位置:首页 > 理论基础 > 数据结构算法

数据结构迷宫问题

2016-07-28 09:37 627 查看
#include<iostream>
#include<stack>
using namespace std;

#define N 10

struct Pos
{
size_t _row;
size_t _col;
};

void InitMaze(int maze[]
)//初始化
{
FILE* fOut = fopen("MazeMap.txt", "r");
if (fOut == NULL)
{
cout << "Open MazeMap.txt fail!" << endl;
exit(-1);
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N;)
{
//int temp;
//cin >> temp;
char ch = fgetc(fOut);
if (ch == EOF)
{
cout << "MazeMap Error!" << endl;
exit(-1);
}
if (ch == '1' || ch == '0')
{
maze[i][j] = ch - '0';
++j;
}
}
}
fclose(fOut);
}
void PrintMaze(int maze[]
)
{
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
cout << maze[i][j] << " ";
}
cout << endl;
}
cout << endl;
}

//int** f(int N)//创建二维数组
//{
//	int** array = new int*
;
//	for (int i = 0; i < N; ++i)
//	{
//		array[i] = new int
;
//	}
//
//}

bool CheckIsAccess(int maze[]
, 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[]
, Pos entry, stack<Pos>& paths)
{
paths.push(entry);
maze[entry._row][entry._col] = 2;
while (!paths.empty())
{
Pos cur = paths.top();
Pos next = cur;

if (cur._row == N-1)
{
return true;
}

//上
next._row -= 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._col += 1;
if (CheckIsAccess(maze, next))
{
paths.push(next);
maze[next._row][next._col] = 2;
continue;
}

//出栈栈顶位置,进行回溯
Pos tmp = paths.top();
maze[tmp._row][tmp._col] = 3;
paths.pop();
}
return false;
}

int main()
{
int mazeArray

= { 0 };
InitMaze(mazeArray);
PrintMaze(mazeArray);

stack<Pos> paths;
Pos entry = { 2, 0 };
bool ret = GetMazePath(mazeArray, entry, paths);
if (ret)
{
cout << "成功走出迷宫" << endl;
PrintMaze(mazeArray);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: