題目鏈接:
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;
}