HDU - 2757 Ocean Currents (BFS+优先队列)

本文介绍了一个利用BFS(广度优先搜索)结合优先队列解决的算法问题,目标是从起点到终点寻找路径,使得路径上的能量消耗最小。文章详细描述了如何通过方向判断消耗,并给出了具体的实现代码。

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

题意:求从开始点到目标点的最小的能量消耗,如果下一格的风向和当前的一样的话,消耗为0,否则为1,一共8个方向,其实方向是0

思路:BFS的基础上还要加上优先队列来取能量的最小值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 1010;
const int INF = 0x3f3f3f3f;

struct node{
	int x,y,c;
	bool operator <(const node &a)const{
		return c > a.c;
	}
}tmp;
int n,m,sx,sy,ex,ey;
char map[MAXN][MAXN];
int f[MAXN][MAXN];
int dir[8][2]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};

void bfs(){
	priority_queue<node> q;
	node a = {sx,sy,0};
	q.push(a);
	while (!q.empty()){
		tmp = q.top();
		q.pop();
		int tx = tmp.x,ty = tmp.y;
		if (tx == ex && ty == ey)
			return;
		int cost;
		for (int i = 0; i < 8; i++){
			tx = tmp.x + dir[i][0];
			ty = tmp.y + dir[i][1];
			if (tx >= 0 && tx < n && ty >= 0 && ty < m){
				int d = (map[tmp.x][tmp.y]-'0');
				if (i == d)
					cost = tmp.c;
				else cost = tmp.c + 1;
				node cur = {tx,ty,cost};
				if (f[tx][ty] > cost){
					f[tx][ty] = cost;
					q.push(cur);
				}
			}
		}
	}
}

int main(){
	while (scanf("%d%d",&n,&m) != EOF){
		for (int i = 0; i < n; i++)
			scanf("%s",map[i]);
		int t;
		scanf("%d",&t);
		while (t--){
			for (int i = 0; i <= n; i++)
				for (int j = 0; j <= m; j++)
					f[i][j] = INF;
			scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
			sx--,sy--,ex--,ey--;
			f[sx][sy] = 0;
			bfs();
			printf("%d\n",f[ex][ey]);
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值