POJ - 2312 Battle City (bfs + priority_queue)

原题: 传送门
题意: 给你一个地图,各字母含义如下:
Y:你所在的位置
T:目标位置
B:砖头墙(先开炮打碎砖头,花费1,再通过,花费1,一共花费为2)
E:空地(直接通过,花费为1)
S:钢铁墙(不能走)
R:小河(不能走)
题目就是要求从Y到T的最小花费
思路: 直接bfs套上
注意: 由于存在花费不同的情况,所以需要用优先队列把花费小的放在前面
注意: 由于存在花费不同的情况,所以需要用优先队列把花费小的放在前面
注意: 由于存在花费不同的情况,所以需要用优先队列把花费小的放在前面
(重要的事情说三遍)
ps: 本菜鸡由于没有用优先队列wa了几发,枯了

Code:

#include<iostream>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int MAX = 307;
int n, m;
char mp[MAX][MAX];
bool vis[MAX][MAX];
struct node {
	int x, y, dis;
	bool operator < (const node& other) const{
		return dis > other.dis;
	}
};
int d[4][2] = {{0,-1},{-1,0},{0,1},{1,0}};
priority_queue<node> q;
bool is_in(int x, int y) {
	return x >= 0 && x < m && y >= 0 && y < n;
}
int bfs(int x, int y) {
	vis[x][y] = true;
	node nd;nd.x=x;nd.y=y;nd.dis=0;
	q.push(nd);

	while (!q.empty()) {
		node u = q.top();q.pop();
		
		if (mp[u.x][u.y] == 'T') {
			return u.dis;
		}
		for (int i=0;i<4;i++) {
			int nx = u.x + d[i][0], ny = u.y + d[i][1];
			if (is_in(nx, ny) && mp[nx][ny] != 'S' && mp[nx][ny] != 'R' && !vis[nx][ny]) {
				nd.x = nx;
				nd.y = ny;
				if (mp[nx][ny] == 'B') {
					nd.dis = u.dis + 2;
				} else {
					nd.dis = u.dis + 1;
				}
				q.push(nd);
				vis[nx][ny] = true;
			}
		}
	}
	return -1;
}
void init() {
	while (!q.empty()) {
		q.pop();
	}
	for (int i=0;i<m;i++)
		for (int j=0;j<n;j++) {
			vis[i][j] = false;
		}
}
int main()
{
	int sx, sy;
	while (cin>>m>>n && n && m) {
		init();
		for (int i=0;i<m;i++){
				cin>>mp[i];
				for (int j=0;j<n;j++) {
					if (mp[i][j] == 'Y') {
						sx = i;
						sy = j;
					}
				}
			}
		cout<<bfs(sx, sy)<<endl;
	}
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值