数据结构之栈的应用(迷宫问题)

#include <iostream>
#include <stack>
using namespace std;
#define maxn 100
int m, n; //长宽

int dir[4][2] = {0, 1, -1, 0, 0, -1, 1, 0}; //下,左右,上(顺时针方向)
int maze[maxn][maxn];
int visited[maxn][maxn];

struct Point
{
int x;
int y;
};

bool MazePath() //选择路径
{
stack<Point> s;
Point p;
Point temp;
p.x = 1;
p.y = 1;
visited[1][1] = 1;
s.push(p);
int i;
while (!s.empty())
{
p = s.top();
s.pop();
i = 0;
while (i < 4)
{

temp.x = p.x + dir[i][0];
temp.y = p.y + dir[i][1];
if (temp.x <= m && temp.y <= n && !visited[temp.x][temp.y] && maze[temp.x][temp.y] == 0)
{
s.push(temp);
visited[temp.x][temp.y] = 1;
p.x = temp.x;
p.y = temp.y;
if (temp.x == m && temp.y == n)
{
return true;
}
else
{
i = 0;
}
//栈顶结点接着试探
}
else
{
i++;
}
}
}
return false;
}

int main()
{
int i, j;
while (cin >> m >> n)
{
memset(maze, 0, sizeof(maze));
memset(visited, 0, sizeof(visited));
for (i = 1; i <= m; i++)
{
for (j = 1;j <= n; j++)
{
cin >> maze[i][j];  //设置迷宫,0代表可通,1代表不通
}
}

if (MazePath())
{
cout << “可达!” << endl;
}
else
{
cout << “不可达!” << endl;
}
}
return 0;
}

/*

 3 3 
  
0 0 1
0 1 1
0 0 0

8 8
 
0 0 1 0 0 0 1 0
0 0 1 0 0 0 1 0
0 0 0 0 1 1 0 0
0 1 1 1 0 0 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 1 0 0
0 1 1 1 0 1 1 0
1 0 0 0 0 0 0 0

*/

    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/xie_dream/article/details/7921001
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞