C++顺序栈深搜求解迷宫

直接上代码,不明白的欢迎评论,看到必回!!!

#include<iostream>
#include<stdio.h>
#define max 100
using namespace std;
int mg[100][100];
typedef struct{
	int x,y,di;
}box;
typedef struct{
	box data[max];
	int top;
}St;
bool mgpath(int xi,int yi,int xe,int ye){
	int x,y,di,find;
	St st;
	st.top=0;
	st.data[st.top].x=xi;
	st.data[st.top].y=yi;
	st.data[st.top].di=-1;
	mg[xi][yi]=-1;
	while(st.top>-1){
		x=st.data[st.top].x;
		y=st.data[st.top].y;
		di=st.data[st.top].di;
		if(x==xe&&y==ye){
			for(int k=0;k<=st.top;k++){
				printf("\t(%d, %d)",st.data[k].x,st.data[k].y);
				if((k+1)%5==0)
				cout<<endl;
			}
			return true;
		}
		find=0;
		while(find==0&&di<4){
			di++;
			switch(di){
				case 0:
					x=st.data[st.top].x-1;
					y=st.data[st.top].y;
					break;
					case 1:
						x=st.data[st.top].x;
						y=st.data[st.top].y+1;
						break;
						case 2:
							x=st.data[st.top].x+1;
							y=st.data[st.top].y;
							break;
							case 3:
								x=st.data[st.top].x;
								y=st.data[st.top].y-1;
								break;
			}
			if(mg[x][y]==0)
			find=1;
		}
		if(find==1){
			st.data[st.top].di=di;
			st.top++;
			st.data[st.top].x=x;
			st.data[st.top].y=y;
			st.data[st.top].di=-1;
			mg[x][y]=-1;
		}
		else{
			mg[st.data[st.top].x][st.data[st.top].y]=0;
			st.top--;
		}
	}
	return false;
}
int main(){
	int x,y;
	cin>>x>>y;
	int i,j;
	for(i=0;i<x;i++)
	for(j=0;j<y;j++)
	cin>>mg[i][j];
	if(!mgpath(1,1,x-2,y-2)){
		cout<<"no way";
	}
	return 0;
}

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值