【简单搜索】迷宫问题

迷宫问题

问题描述

定义一个二维数组:

int maze[5][5] = {

	0, 1, 0, 0, 0,

	0, 1, 0, 1, 0,

	0, 0, 0, 0, 0,

	0, 1, 1, 1, 0,

	0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

思路

就是一个简单的bfs。关键在于记忆最短路径。我的解决方案是在结点结构体中除了有该结点的横纵坐标,还包括它自身的入队序列号(id)以及在到达它之前的前一个结点的入队序列号(pre)

struct node{
	int x, y, id, pre;
}N[50]; 

其实就是建了一个指向前一结点的单链表。
到达终点后,去找到终点的前一个结点,一直找下去直到遍历到起点(我是用递归做的),然后在退层的过程中按要求打印出每个结点的横纵坐标。要注意的地方在于,输出答案时逗号之后还有一个空格,否则提交时会出“Presentation Error”。
其他没有什么了,这题就是Pots的简化版。

代码样例

//K-迷宫问题
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int maze[10][10], vist[10][10];
int direction[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node{
	int x, y, id, pre;
}N[50]; 
int check(int r, int c){
	if(r<0||r>=5||c<0||c>=5||vist[r][c]||maze[r][c]){
		return 1;
	}
	return 0;
}
void print_route(int index){
	if(N[index].pre==-1){
		cout<<"(0, 0)"<<endl;
		return;
	}
	print_route(N[index].pre);
	cout<<"("<<N[index].x<<", "<<N[index].y<<")"<<endl;
}
void bfs(){
	//init()
	memset(vist, 0, sizeof(vist));
	node p, q;
	p.x=0, p.y=0, vist[0][0]=1;
	p.id=0, p.pre=-1;
	int counter=0;
	N[0]=p;
	queue<node> Q;
	Q.push(p);
	while(Q.size()){
		p=Q.front(), Q.pop();
		if(p.x==4&&p.y==4){
			break; 
		}
		for(int i=0; i<4; i++){
			q=p;
			q.x+=direction[i][0];
			q.y+=direction[i][1];
			if(check(q.x, q.y)) continue;
			vist[q.x][q.y]=1;
			counter++;
			q.id=counter,q.pre=p.id;
			N[counter]=q, Q.push(q);
		}
	}
	print_route(p.id); 
}
int main(void){
	for(int i=0; i<5; i++){
		for(int j=0; j<5; j++){
			cin>>maze[i][j];
		}
	}
	bfs();
	return 0;
}

  • 1605集训计划第十一天任务
  • 按时完成
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值