思路 :
- 由于字符串长度只有7,又求最少次数,因此我们想到bfs,复杂度为 O ( 7 ! ) O(7!) O(7!)
- 注意由于我们已经用了map来存距离,不需要额外开一个容器了,直接用map就可以判断某个点是否被搜索过
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <deque>
#include <sstream>
#include <unordered_set>
#include <unordered_map>
#include <bitset>
#define endl '\n'
#define _(a) cout << #a << ": " << (a) << " "
#define one first
#define two second
#define pb push_back
using namespace std;
template<class T> void chkmax(T &a, T b) {a = max(a, b);}
template<class T> void chkmin(T &a, T b) {a = min(a, b);}
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<int, ll> pil;
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
string s;
cin >> s;
unordered_map<string, int> ma;
ma[s] = 0;
queue<string> q;
q.push(s);
while (q.size()) {
string t = q.front(); q.pop();
if (t == "atcoder") {
cout << ma[t];
return 0;
}
for (int i = 0; i < 6; ++ i) {
string now = t;
swap(now[i], now[i + 1]);
if (ma.find(now) == ma.end()) {
ma[now] = ma[t] + 1;
q.push(now);
}
}
}
}