845. 八数码(BFS搜索)

845. 八数码

#include <bits/stdc++.h>
using namespace std;

unordered_map<string, int> mp;
string start;
bool flag;

void bfs(){
    queue<string> q; q.push(start);
    mp[start] = 0;
    
    int dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
    while(q.size()){
        auto t = q.front(); q.pop();
        if(t == "12345678x"){flag = true; return;}
        int index = t.find('x');
        int x = index / 3, y = index % 3;
        for(int i = 0; i < 4; ++i){
            int xx = dx[i] + x, yy = dy[i] + y;
            if(xx < 0 || yy < 0 || xx >= 3 || yy >= 3) continue;
            int distance = mp[t];
            swap(t[index], t[3 * xx + yy]);
            if(!mp[t]){
                mp[t] = distance + 1;
                q.push(t);
            }
            swap(t[index], t[3 * xx + yy]);
        }
    }
}
signed main(){
    start = "";
    for(int i = 0; i < 9; ++i){
        char c; cin >> c;
        start += c;
    }
    
    bfs();
    
    if(!flag) cout << -1 << endl;
    else cout << mp["12345678x"] << endl;
    
    return 0;
}
posted @ 2025-03-21 21:32  awei040519  阅读(13)  评论(0)    收藏  举报