//node_maze.h
#ifndef NODE_MAZE_H
#define NODE_MAZE_H
struct Point
{
int x;
int y;
};
struct node
{
int ord;
Point pt;
int di;
};
#endif
//main.cpp
#include "Stack.h"
#include "node_maze.h"
#include <iostream>
using namespace std;
typedef int MazeType[10][10];
const int num = 20;
Point der[4] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
Status flag[10][10];
MazeType maze;
Status f;
Status print(node e)
{
cout << e.pt.x << " " << e.pt.y << endl;
return OK;
}
Status pass(Point p)
{
if (p.x < 0 || p.x >= 10 || p.y < 0 || p.y >= 10 || flag[p.x][p.y] || maze[p.x][p.y])
return FALSE;
else
return TRUE;
}
Status GetNextpos(Point &pt, Point p, int de)
{
pt.x = p.x + der[de].x;
pt.y = p.y + der[de].y;
return OK;
}
Status MazePath( Point start, Point end)
{
SqStack<node> S;
S.InitStack();
int curstep = 0;
Point curpos = start;
do
{
if (pass(curpos))
{
node e = {++curstep, curpos, 1};
S.Push(e);
flag[curpos.x][curpos.y] = TRUE;
if (e.pt.x == end.x && e.pt.y == end.y)
{
cout << endl << "path...." << endl;
S.StackTraverse(print);
return TRUE;
}
GetNextpos(curpos, curpos, 0);
}
else
{
node e;
if (!S.StackEmpty())
{
S.Pop(e);
while (e.di == 4 && !S.StackEmpty())
{
S.Pop(e);
}
if (e.di < 4)
{
GetNextpos(curpos, e.pt, e.di);
e.di ++;
S.Push(e);
}
}
}
}while (!S.StackEmpty());
return FALSE;
}
//递归的解法
/*
void MazePath(Point end, Point cur)
{
if (pass(cur))
{
flag[cur.x][cur.y] = TRUE;
if (cur.x == end.x && cur.y == end.y)
{
f = true;
}
for (int i = 0; i < 4; i++)
{
Point pt;
pt.x = cur.x + der[i].x;
pt.y = cur.y + der[i].y;
MazePath(end, pt);
}
}
}
*/
int main()
{
int n = num, ival;
Point beg = {1, 1}, end = {8, 8};
cout << "请输入迷宫:" << endl;
f = 0;
for (int i = 0; i < 10; i ++)
{
for (int j = 0; j < 10; j ++)
{
cin >> maze[i][j];
flag[i][j] = 0;
}
}
MazePath(beg, end);
}
/*
1 1 1 1 1 1 1 1 1 1
1 0 0 1 0 0 0 1 0 1
1 0 0 1 0 0 0 1 0 1
1 0 0 0 0 1 1 0 0 1
1 0 1 1 1 0 0 0 0 1
1 0 0 0 1 0 0 0 0 1
1 0 1 0 0 0 1 0 0 1
1 0 1 1 1 0 1 1 0 1
1 1 0 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1
*/
数据结构 栈的应用 -- 迷宫的实现
最新推荐文章于 2020-11-28 16:38:20 发布