啊哈算法dfs-bfs

题目为解救小哈

第一种为dfs

#include <iostream>

using namespace std;
int dx,dy,n,m,imin=99999999;
int a[1000][1000],book[1000][1000];
void dfs(int x,int y,int step)
{
	int next[4][2]=
	{
		{0,1},
		{1,0},
		{0,-1},
		{-1,0}
	};
	int tx,ty;
	if(x==dx&&y==dy)
	{
		if(step<imin) imin=step;
		return ;
	}
	
	for(int k=0;k<4;k++)//枚举4个方向 
	{
		tx=x+next[k][0];
		ty=y+next[k][1]; 
		if(tx<1||tx>n||ty<1||ty>m) 
			continue;
		if(a[tx][ty]==0&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,step+1);
			book[tx][ty]=0;
			
		}
		
	}
	return ;
}
int main()
{
	int sx,sy;
	cin >> n >> m;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++)
			cin >> a[i][j];
	cin >> sx >> sy >> dx >> dy;
	book[sx][sy]=1;//从当前位置开始搜索
	dfs(sx,sy,0);
	cout << imin;
	return 0;

}

第二种为bfs

#include <iostream>
#include <queue>
using namespace std;
int sx,sy,dx,dy,n,m,imin=99999999;
int a[100][100],book[100][100];
struct node
{
	int x,y,s;	
	//x,y存坐标,s存步数 
};

void bfs(int x,int y)
{
	int next[4][2]={
	{0,1},
	{1,0},
	{0,-1},
	{-1,0}
	};//上下左右移动 
	queue<node> p;
	node head,tail;//一个头一个尾 
	head.x=x;
	head.y=y;
	head.s=0;//这三行是存个头 
	p.push(head);//头塞进队列 
	while(!p.empty())//检查是否为空 
	{
		head=p.front(); //将第一个元素变成头 
		p.pop();//删去第一个检查过的元素便于往后查找 
		if(head.x==dx&&head.y==dy)//查找到直接退出,bfs一定是最优解 
		{
			imin=head.s;
			return;
		}
		for(int k=0;k<4;k++)//枚举四个方向 
		{
			tail.x=head.x+next[k][0];
			tail.y=head.y+next[k][1];
			if(tail.x<1||tail.x>n||tail.y<1|tail.y>m) continue;//判断越界 
			if(a[tail.x][tail.y]==0&&book[tail.x][tail.y]==0)
			{
				book[tail.x][tail.y]=1; //标记 
				tail.s=head.s+1; //下一次步数=这次+1 
				p.push(tail);//这次的尾变成下一次的头 
				
			}
			
		}
	}

} 
int main()
{
	cin >> n >> m;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			cin >> a[i][j];
	cin >> sx >> sy >> dx >> dy;
	book[sx][sy]=1;//将开始位置标记 
	bfs(sx,sy);
	cout << imin ;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值