hdu 2822 Dogs

本文详细介绍了如何使用优先队列和双搜索算法解决迷宫问题,通过优先选择步数最小的路径进行广度优先搜索,提高了效率。文章包括代码实现和分析过程,适合对算法优化感兴趣的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=2822

分析:遇到'.'(挖隧道)的时候才需要步数加1,'X'是一个整体,利用优先队列选择步数最小的开始广搜

不过这样效率比较低,可以用双搜加快效率

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;

const int NM=1005;
int a[4][2]={-1,0,1,0,0,1,0,-1};
int vis[NM][NM],n,m,x1,y1,x2,y2;
char str[NM][NM];
struct Dog{
	int x,y,ans;
};
bool operator < (struct Dog A,struct Dog B)
{
	if(A.ans>B.ans) return 1;
	else return 0;
}

void BFS()
{
	priority_queue<Dog>pq1;
	Dog t,p;
	int i,j;
	
	for(i=0;i<n;i++)
		for(j=0;j<m;j++)
			vis[i][j]=0;
	t.x=x1,t.y=y1;
	t.ans=0;
	vis[t.x][t.y]=1;
	pq1.push(t);
	while(!pq1.empty())
	{
		t=pq1.top();pq1.pop();
		if(t.x==x2&&t.y==y2)
		{
			printf("%d\n",t.ans);
			return;
		}
		for(i=0;i<4;i++)
		{
			p.x=t.x+a[i][0],p.y=t.y+a[i][1];
			p.ans=t.ans;
			if(p.x>=0&&p.x<n&&p.y>=0&&p.y<m&&!vis[p.x][p.y])
			{
				if(str[p.x][p.y]=='.')
					p.ans++;
				vis[p.x][p.y]=1;
				pq1.push(p);
			}
		}
	}
}

int main()
{
	int i;
	while(scanf("%d%d",&n,&m)&&(n||m))
	{
		for(i=0;i<n;i++)
			scanf("%s",str[i]);
		scanf("%d%d",&x1,&y1);
		scanf("%d%d",&x2,&y2);
		x1-=1,y1-=1;
		x2-=1,y2-=1;
		BFS();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值