一般路径求解:
#pragma once
#include <iostream>
#include <Windows.h>
#include <stack>
#include <assert.h>
using namespace std;
const size_t N = 15;
void InitMaze(int maze[][N], size_t n) //写入迷宫
{
FILE* pp = fopen("ak.txt", "r");
assert(pp);
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n;)
{
char ch = fgetc(pp); //转换为二进制输出
if (ch == '0' || ch == '1')
{
maze[i][j] = ch - '0';
++j;
}
}
}
}
void PrintMaze(int maze[][N], size_t n) //打印迷宫
{
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{
cout << maze[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
struct Pos
{
int _row; //行
int _col; //列
};
//0为通路 其他均不通
bool CheckAccess(int maze[][N], int n, Pos pos) //检查位置是否为通路
{
if ((pos._row < n && pos._row >= 0)
&& (pos._col < n && pos._col >= 0)
&& (maze[pos._row][pos._col] == 0))
{
return true;
}
return false;
}
bool GetMazePath(int maze[][N], size_t n, Pos entry) //获取路径
{
stack<Pos> path;
path.push(entry);
while (!path.empty())
{
Pos cur = path.top(); //当前位置压入栈顶
//找到出口
if (cur._row == n - 1)
{
return true;
}
Pos next = cur;
maze[cur._row][cur._col] = 2; //走过的路程标记为2
//代码实现的方向次序决定执行的次序,如果在优先方向找到通路,则不会在找其他通路
//上
next = cur;
next._row--;
if (CheckAccess(maze, n, next))
{
path.push(next);
continue;
}
//右
next = cur;
next._col++;
if (CheckAccess(maze, n, next))
{
path.push(next);
continue;
}
//下
next = cur;
next._row++;
if (CheckAccess(maze, n, next))
{
path.push(next);
continue;
}
//左
next = cur;
next._col--;
if (CheckAccess(maze, n, next))
{
path.push(next);
continue;
}
Pos top = path.top();
maze[top._row][top._col] = 3; //如果此时走的路不通,回溯时,走的路标记为3
path.pop();
}
return false;
}
//bool GetMazePathR(int maze[][N], size_t n, Pos cur,
//stack<Pos>& shortPath, stack<Pos>& path)
//{
// path.push(cur);
//}
#include"maze.h"
void test()
{
int maze[N][N];
InitMaze(maze, N);
PrintMaze(maze, N);
stack<Pos> path;
Pos entry;
entry._row = 2;
entry._col = 0;
maze[2][0] = 2;
GetMazePath(maze, N, entry);
PrintMaze(maze, N);
}
int main()
{
test();
system("pause");
return 0;
}