計蒜客-蒜頭君回家-bfs

題目鏈接
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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章