XDOJ迷宫问题


title: 迷宫问题
date: 2022-05-13 17:51:40
tags: C语言
categories: 数据结构


问题输入

一组数据,输入数据第1行为两个正整数m和n,m表示迷宫高度,n表示迷宫宽度,m<100,n<100;第2行为两个整数,分表表示起点的行列位置;第3为两个整数,分别表示终点的行列位置;其后为m行数据,每行n个整数,表示迷宫对应位置的状态,0表示通路,1表示障碍。

问题输出

以三元组形式(见P105)输出从起点到终点搜索到的第一条通路,没有则输出no

输入样例

8 8

1 1

8 8

0 0 1 0 0 0 1 0

0 0 1 1 0 0 1 0

0 0 0 0 1 1 0 0

0 1 1 1 0 0 0 0

0 0 0 1 1 0 0 0

0 1 0 0 0 1 0 0

0 1 1 1 0 1 1 0

1 1 0 0 0 0 0 0

输出样例

(1,1,1),(1,2,2),(2,2,2),(3,2,3),(3,1,2),(4,1,2),(5,1,1),(5,2,1),(5,3,2),(6,3,1),(6,4,1),(6,5,2),(7,5,2),(8,5,1),(8,6,1),(8,7,1),(8,8,1)

#include<stdio.h>
#include<stdlib.h>
#define Maxsize 10000
int **map;
typedef struct{
	int x;
	int y;
	int di;
}seat;
typedef struct{
	seat *base;
	seat *top;
	int size;
}sqStack;  
int InitStack(sqStack *S){
	S->base=(seat *)malloc(sizeof(seat)*Maxsize);
	if(!S->base) exit(0);
	S->size=Maxsize;
	S->top=S->base;
	return 1;
}
int Push(sqStack *S,seat a){
	*S->top++=a;
	return 1;
}
int GetTop(sqStack *S,seat *a){
	if(S->base==S->top) return 0;
	else *a=*--S->top;
	return 1;
}
void Map(int x,int y){
	map=(int **)malloc(sizeof(int *)*x);
	for(int i=0;i<x;i++){
		map[i]=(int *)malloc(sizeof(int)*y);
	}
	for(int i=0;i<x;i++){
	   map[i][0]=1;
	   map[i][y-1]=1;
	}
	for(int j=0;j<y;j++){
		map[0][j]=1;
		map[x-1][j]=1;
	}
	for(int i=1;i<x-1;i++){
		for(int j=1;j<y-1;j++){
			scanf("%d",&map[i][j]);
		}
	}
	
}

int findPath(int x1,int y1,int x2,int y2){
	sqStack q;
	InitStack(&q);
	seat a,b,c;
	int d,m,n,f;
	a.x=x1;
	a.y=y1;
	map[x1][y1]=-1;
	a.di=0;
	Push(&q,a);

	while(q.top!=q.base){
		if((q.top-1)->x==x2&&(q.top-1)->y==y2) break;
		d=(q.top-1)->di;
		f=0;
		while(d<=4){
            d++;
			switch(d){
			  case 1: m=(q.top-1)->x; n=(q.top-1)->y+1; break;
			  case 2: m=(q.top-1)->x+1; n=(q.top-1)->y; break;
			  case 3: m=(q.top-1)->x; n=(q.top-1)->y-1; break;
			  case 4: m=(q.top-1)->x-1; n=(q.top-1)->y; break;
			  	}	
			  if(map[m][n]==0){
			  	map[m][n]=-1;
			  	(q.top-1)->di=d;
			  	b.x=m;
			  	b.y=n;
			  	b.di=0;
			  	Push(&q,b);
			  	f=1;
			  	break;
			  }
			
		}
		if(f==0){
			GetTop(&q,&c);
			map[c.x][c.y]=3;
		}
	}
	if((q.top-1)->x==x2&&(q.top-1)->y==y2){
		for(seat *i=q.base;i<(q.top-1);i++){
			printf("(%d,%d,%d),",i->x,i->y,i->di);
		}
		printf("(%d,%d,%d)",(q.top-1)->x,(q.top-1)->y,1);
		return 0;
	}
	else printf("no");
}
int main(){
	int X,Y,ax,ay,bx,by;
	scanf("%d %d %d %d %d %d",&X,&Y,&ax,&ay,&bx,&by);
	Map(X+2,Y+2); //初始化迷宫,把迷宫四周围上1;
	findPath(ax,ay,bx,by);
} 

欢迎关注博客LeoCache 更多上机代码合集

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LeoCache

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值