数据结构 栈的应用 -- 迷宫的实现

//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
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值