数据结构栈——迷宫问题C++

1、方向试探
typedef struct {
int incX,incY;//x,y方向的增量
}Direction;
Direction direct[4];

directincXincY
001
110
20-1
3-10

2、Box temp;

xydir

栈中数据元素的组织
typedef struct{
int x,y;
int dir;//当前元素的位置和方向
}Box;
3、栈
typedef struct{
Box data[MaxSize];
int top;
}SqStack;

4、具体代码
SqStack.h

#ifndef TEST_H
#define TEST_H
#define MaxSize 50//定义栈中元素的最大个数
//栈中数据元素的组织
typedef struct{
	int x,y;
	int dir;//当前元素的位置和方向 
}Box;

//栈 
typedef struct{
	Box data[MaxSize];
	int top;
}SqStack; 

//方向试探 
typedef struct {
	int incX,incY;//x,y方向的增量 
}Direction;  


//初始化 
void InitStack(SqStack &S);
//判栈空 
bool StackEmpty(SqStack S); 
//进栈
bool Push(SqStack &S,Box x); 
//出栈 
bool Pop(SqStack &S,Box &x);
//读取栈顶元素
//bool GetTop(SqStack S,Elemtype &x); 
//打印栈中元素
void print(SqStack S);

SqStack.cpp

#include "SqStack.h"
#include <iostream>
//初始化 
void InitStack(SqStack &S){
	S.top=-1;
}
//判栈空 
bool StackEmpty(SqStack S){
	if(S.top==-1) 
	    return true;
	else 
	    return false;
}
//进栈
bool Push(SqStack &S,Box x){
	if(S.top==MaxSize-1) return false;
	S.top++;
	S.data[S.top]=x;//指针加一,在入栈 
	return true;
}
//出栈 
bool Pop(SqStack &S,Box &x){
	if(S.top==-1) return false;
	x=S.data[S.top--];//先出栈,指针减一 
	return false;
}
//迷宫问题 
bool findpath(int maze[6][6],Direction direct[],SqStack &S){
	Box temp;
	int x,y,di;//当前坐标和方向
	int line,col;//下一个坐标
	maze[1][1]=-1;
	temp={1,1,-1}; 
	Push(S,temp);
	while(!StackEmpty(S)){
		Pop(S,temp);
		x=temp.x; y=temp.y; di=temp.dir+1;
		while(di<4){
			line=x+direct[di].incX;
			col=y+direct[di].incY;
			if(maze[line][col]==0){
                temp={x,y,di};
				Push(S,temp);
				x=line; y=col; maze[x][y]=-1;
				if(x==4&&y==4) return true;//迷宫有路
				else di=0;
			}
			else{
				di++;
			}
		}
	}
	return false;
	 
} 
void print(SqStack S){
	if(S.top==-1)
	   printf("栈中元素为空");
	while(S.top!=-1){
		printf("(%d,%d)  ",S.data[S.top].x,S.data[S.top].y);
		S.top--;
	} 
	printf("\n");
}

SqStack_main.cpp

#include <iostream>
using namespace std;
#include "SqStack.h"

int main(int argc, char** argv) {
	SqStack S;
	int maze[6][6]={
	{1,1,1,1,1,1},
	{1,0,0,1,1,1},
	{1,0,0,0,0,1},
	{1,0,1,1,1,1},
	{1,0,0,0,0,1},
	{1,1,1,1,1,1}
	};
	Direction direct[4]={{0,1},{1,0},{0,-1},{-1,0}};
	//初始化 
	InitStack(S);
	//判栈空 
	StackEmpty(S); 
	//迷宫问题 
    bool y=findpath(maze,direct,S);
    printf("结果是:%s\n",y==true?"找到出口":"不成功");
    print(S);
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值