leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0773.cpp (1681B)


      1 class Solution {
      2     using type_t = pair<uint32_t, uint32_t>;
      3 
      4     static type_t encode(const vector<vector<int>> &board) {
      5         uint32_t n2p = 0; // number to position
      6         uint32_t p2n = 0; // position to number
      7 
      8         for (int i = 0; i < 2; i++) {
      9             for (int j = 0; j < 3; j++) {
     10                 const int idx = i * 3 + j;
     11                 n2p |= idx << (board[i][j] * 3);
     12                 p2n |= board[i][j] << (idx * 3);
     13             }
     14         }
     15 
     16         return {n2p, p2n};
     17     }
     18 
     19   public:
     20     int slidingPuzzle(const vector<vector<int>> &board) const {
     21         static const vector<vector<int>> adj = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
     22 
     23         unordered_set<uint32_t> seen;
     24         queue<type_t> q;
     25 
     26         q.push(encode(board));
     27         for (int lvl = 0; !q.empty(); lvl++) {
     28             for (int k = size(q); k > 0; k--) {
     29                 const auto [n2p, p2n] = q.front();
     30                 q.pop();
     31 
     32                 if (n2p == 0x23445) return lvl;
     33 
     34                 const auto p = n2p & 0x7;                    // position of zero
     35                 for (const auto sp : adj[p]) {               // position to swap
     36                     const auto sn = (p2n >> (sp * 3)) & 0x7; // number to swap
     37 
     38                     const auto sn2p = (n2p & ~((0x7 << (sn * 3)) | (0x7 << (0 * 0)))) | (p << (sn * 3)) | sp;
     39                     const auto sp2n = (p2n & ~((0x7 << (sp * 3)) | (0x7 << (p * 3)))) | (sn << (p * 3));
     40 
     41                     if (!seen.count(sn2p)) {
     42                         q.emplace(sn2p, sp2n);
     43                         seen.insert(sn2p);
     44                     }
     45                 }
     46             }
     47         }
     48 
     49         return -1;
     50     }
     51 };