F - 迷宫问题(bfs)

在这里插入图片描述

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<map>
#include<vector>
#include<queue>
using namespace std;
int a[106][106];
int prond=0,last=1;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
struct node{//用来储存路径
	int x,y;
	int pre;
}n[100];
void print(int s)//递归输出路径
{
	if(n[s].pre!=-1)
	{
		print(n[s].pre);
		cout<<"("<<n[s].x<<", "<<n[s].y<<")"<<endl;
	 } 
} 
void bfs(int c,int b)
{

	n[prond].x=c;
	n[prond].y=b;
	n[prond].pre=-1;
	while(prond<last)
	{
			for(int i=0;i<4;i++)//遍历四个方向
	    {
		int x1=n[prond].x+dx[i];
		int y1=n[prond].y+dy[i];
		if(x1<0||x1>=5||y1<0||y1>=5||a[x1][y1]==1)
		continue;//该位置不能走下去,用continue继续执行下面语句,与dfs不同,不是return;
		else
		{
				a[x1][y1]=1;
		n[last].x=x1;
		n[last].y=y1;
		n[last].pre=prond;
		last++;
		}
	
		if(x1==4&&y1==4)//到达目标位置
		print(prond);
    	}
    	prond++;
	}	
}
int main() 
{
	for(int i=0;i<5;i++)
	{
		for(int j=0;j<5;j++)
		{
			cin>>a[i][j];
			
		}
	}
	cout<<"(0, 0)"<<endl;
	bfs(0, 0);
	cout<<"(4, 4)"<<endl;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值