藍橋杯 PREV-44 青蛙跳杯子(bfs)

題目鏈接:

PREV-44 青蛙跳杯子

思路:

我們採用搜索的方式,尋找每一種情況的所有下一種可能情況,並用map標記已經遍歷過的情況;
像此種類似尋求最短路的搜索用bfs更加高效;

代碼:

#include<bits/stdc++.h>

using namespace std;

map<string, int> vst;
string s, t;
queue<string> que;
inline void check(int x, int & y, string & str) {
	if(x < 0 || x >= str.length()) return;
	string tmp = str;
	swap(tmp[x], tmp[y]);
	if(vst[tmp] == 0) {	
		if(tmp == t) cout << vst[str], exit(0);
		que.push(tmp), vst[tmp] = vst[str] + 1;
	}
}
void bfs() {	
	que.push(s);
	vst[s] = 1;
	while(!que.empty()) {
		string str = que.front();
		que.pop();
		for(int i = 0; i < str.length(); i++) {
			if(str[i] != '*') continue;
			for(int j = -3; j <= 3; j++) if(j) check(i + j, i, str);
		}
	}
}

int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);
#endif
	cin >> s >> t;
	bfs();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章