数据结构之栈的应用(迷宫问题)
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
*/
#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
*/
相关文章推荐
- 栈的应用-迷宫问题-数据结构
- 数据结构之 栈应用---老鼠迷宫问题
- 数据结构5————栈的应用2-非递归解决迷宫和马踏棋盘问题
- 经典数据结构之栈的应用-迷宫问题
- 第六周--数据结构之自建算法库之迷宫问题(用栈结构)
- 数据结构 — 迷宫问题
- 算法:迷宫求解(栈的应用)-数据结构(8)
- 数据结构实践——迷宫问题之图深度优先遍历解法
- 数据结构之链式队列与链式栈的应用-球钟问题
- 队列的基本操作应用---舞伴问题(数据结构实验项目三)
- 数据结构之栈的应用----迷宫求解
- 16、数据结构笔记之十六栈的应用之栈与递归之汉诺塔问题
- 数据结构实践——迷宫问题之图深度优先遍历解法
- 第六周--数据结构之自建算法库之迷宫问题(用队列)
- 数据结构实验(严蔚敏版)2.9迷宫问题
- 数据结构-栈应用-迷宫
- 数据结构之迷宫问题
- 10、数据结构笔记之十栈的应用之迷宫求解实现
- 数据结构与算法-实验3-自定义栈,并实现走迷宫问题
- 数据结构之迷宫问题