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

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

2012-08-29 16:40 363 查看
#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

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: