bfs-迷宫问题--输出路径

7 篇文章 1 订阅
7 篇文章 0 订阅

迷宫问题
题意:由0和1 构成迷宫,只有0可以走,请输出,从{0,0}到{4,4}的最短路径
思路:利用广搜,搜索时并且存储有用路径,此时的路径需要存进当前结构中,因为程序过程中, 头会被弹出,无法回溯
特别注意格式,逗号后还有个空格

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#include<stack>
#define x first
#define y second
#define met(a,b) memset(a,b,sizeof a);
using namespace std;
typedef long long ll;
const int N=1e6+10;
int xx[4][2]= {{0,1},{0,-1},{-1,0},{1,0}};//四个方向
//int xx[8][2]= {{-1,0},{0,-1},{1,0},{0,1},{1,1},{-1,1},{-1,-1},{1,-1}};//八个方向
//int xx[8][2]= {{2,1},{-2,1},{1,2},{1,-2},{2,-1},{-2,-1},{-1,2},{-1,-2}};//马的八个方向
//int xx[6][3]= {{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}};//三维方向
int a[1005][1005];
int book[1005][1005];
int n,m;
int res;
int f;

struct node {
	int x,y,s;
	pair<int,int>lu[50];
};
node start,pre,nt;
queue<node>q;
void bfs(int x,int y) {
	start.x=x;
	start.y=y;
	start.s=1;
	start.lu[start.s]= {1,1};
	q.push(start);
	while(!q.empty()) {
		int xt,yt;
		pre=q.front();
		q.pop();
		if(pre.x==5&&pre.y==5) {
			for(int j=1; j<=pre.s; ++j) {
				printf("(%d, %d)\n",pre.lu[j].x-1,pre.lu[j].y-1);
			}
			return ;
		}
		for(int i=0; i<4; i++) {
			xt=pre.x+xx[i][0];
			yt=pre.y+xx[i][1];
			nt=pre;
			nt.s++;
			if(xt<1||xt>5||yt<1||yt>5)continue;
			if((!a[xt][yt])&&(!book[xt][yt])) {
				book[xt][yt]=1;
				nt.x=xt;
				nt.y=yt;
				nt.lu[nt.s]= {xt,yt};
				q.push(nt);
			}
		}
	}
}

int main() {
	for(int i=1; i<=5; i++) {
		for(int j=1; j<=5; j++) {
			cin>>a[i][j];
		}
	}
	met(book,0);
	book[1][1]=1;
	bfs(1,1);
//	q.pop();
//	cout<<q.front().s;
}

此时数据较水,直接输出样例也可

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值