计蒜客-蒜头君回家-bfs

12 篇文章 0 订阅
6 篇文章 0 订阅

题目链接
bfs广搜,从S到P+从T到P的所有求最小值输出就好,需要注意的地方

  1. 采用了STL的map,map默认按key值排序,故当使用自定义结构体时,应当在结构体内重构比较运算符,一开始只是简单比较了point的x值,后来插入有误,检查后发现当x值相等时便覆盖了相同x值的映射
  2. 采用的point结构体的cnt值变化后,作为映射的key值也会变化
    AC代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2005;
int to[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int n, m;
char amap[maxn][maxn];
bool vis[maxn][maxn], flag;
struct point{
	int x, y, cnt;
	point(int _x, int _y, int _cnt){
		x = _x;
		y = _y;
		cnt = _cnt;
	}
	bool operator < (point const &a) const {
		return a.cnt >cnt;
	}
};

struct spoint{
	int x, y;
	spoint(int _x, int _y){
		x = _x;
		y = _y;
	}
	bool operator < (spoint const &a) const {
		if(a.x == x)
			return a.y < y;
		return a.x < x;
	}
};

point st = point(0, 0, 0);
point en = point(0, 0, 0);
map<spoint, int>fir;
map<int, spoint>sec;

void bfs(point s){
	queue<point>que;
	que.push(s);
	vis[s.x][s.y] = true;
	while(!que.empty()){
		point temp = que.front();
		que.pop();
		for(int i = 0; i < 4; i++){
			point t = temp;
			t.x += to[i][0];
			t.y += to[i][1];
			if((t.x >= 0) && (t.x < n) && (t.y >= 0) && (t.y < m) &&
							(!vis[t.x][t.y]) && (amap[t.x][t.y] != '#')){
				t.cnt++;
				vis[t.x][t.y] = true;
				que.push(t);
				if(amap[t.x][t.y] == 'P'){
					spoint ap = spoint(t.x, t.y);
					if(flag)
						fir.insert(pair<spoint, int>(ap, t.cnt));
					else
						fir[ap] += t.cnt;
				}
			}
		}
	}
}

int main(){
	cin>>n>>m;
	char c;
	for(int i = 0; i < n; i++){
		for(int j = 0; j < m; j++)
		{
			cin>>c;
			amap[i][j] = c;
			if(c == 'S'){
				st.x = i;
				st.y = j;
				st.cnt = 0;
			}
			else if(c == 'T'){
				en.x = i;
				en.y = j;
				en.cnt = 0;
			}
		}
	}
	memset(vis, false, sizeof(vis));
	flag = true;
	bfs(st);
	memset(vis, false, sizeof(vis));
	flag = false;
	bfs(en);
	for(map<spoint, int>::iterator it = fir.begin(); it != fir.end(); ++it)
		sec.insert(pair<int, spoint>(it->second, it->first));
	map<int, spoint>::iterator it = sec.begin();
	cout<<it->first<<endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值