cpp#include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<unordered_map> using namespace std; int dx[4] = { 1,-1,0,0 }; int dy[4] = { 0,0,-1,1 }; int bfs(string state) { queue<string>q; unordered_map<string, int>d; q.push(state); d[state] = 0; while (q.size()) { auto t = q.front(); int dis = d[t]; int k = t.find('x'); int x = k / 3, y = k % 3; q.pop(); string end = "12345678x"; if (t == end)return d[t]; for (int i = 0; i < 4; i++) { int a = x + dx[i], b = y + dy[i]; if (a >= 0 && a < 3 && b >= 0 && b < 3) { swap(t[a * 3 + b], t[k]); if (!d.count(t)) { d[t] = dis + 1; q.push(t); } swap(t[a * 3 + b], t[k]); } } } return -1; } int main() { string state; for (int i = 0; i < 9; i++) { char s; cin >> s; state += s; } cout << bfs(state); return 0; }
算法.bfs八数码
丰海洋2024-02-11 19:26