Leetcode-773

Sliding Puzzle

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <unordered_set>

class Solution {
public:
    int slidingPuzzle(std::vector<std::vector<int>>& board) {
        std::string start = "";
        int p = 0;
        for (auto& row : board) {
            for (auto& c : row) {
                start += (c + '0');
            }
        }
        if (start == "123450") {
            return 0;
        }
        for (int i = 0; i < 6; ++i) {
            if (start[i] == '0') {
                p = i;
                break;
            }
        }
        
        std::vector<std::vector<int>> dirs = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
        std::unordered_set<std::string> visited = { start };
        std::queue<std::pair<std::string, std::pair<int, int>>> q;
        q.push({start, {0, p}});
        while (!q.empty()) {
            std::string u = q.front().first;
            int d = q.front().second.first;
            int p = q.front().second.second;
            q.pop();
            for (auto& v : dirs[p]) {
                std::swap(u[p], u[v]);
                if (!visited.count(u)) {
                    if (u == "123450") {
                        return d + 1;
                    }
                    q.push({u, {d + 1, v}});
                    visited.insert(u);
                }
                std::swap(u[p], u[v]);
            }
        }
        return -1;
    }
};

Leetcode-773

Licensed under CC BY-NC-SA 4.0