1 条题解

  • 1
    @ 2024-12-4 9:58:51
    #include <bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int N = 1e6 + 10, INF = 0x3f3f3f3f, MOD = 1E9 + 7;
    string s, target = "123804765";
    int d[][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
    int bfs() {
        map<string, int> mp;
        queue<string> q;
        q.push(s), mp[s] = 1;
        while (q.size()) {
            auto u = q.front(); q.pop();
            if (u == target) return mp[u] - 1;
            for (int i = 0; i < 4; i++) {
                int p = u.find('0');
                int x = p / 3 + d[i][0], y = p % 3 + d[i][1];
                if (x < 0 || x >= 3 || y < 0 || y >= 3) continue;
                string v(u);
                swap(v[p], v[x * 3 + y]);
                if (mp[v]) continue;
                q.push(v), mp[v] = mp[u] + 1;
            }
        }
        return -1;
    }
    int main(int argc, char* argv[]) {
        cin >> s, cout << bfs();
        return 0;
    }
    
    • 1

    信息

    ID
    526
    时间
    1000ms
    内存
    128MiB
    难度
    1
    标签
    递交数
    116
    已通过
    94
    上传者