Advertisement
nikunjsoni

773

Apr 26th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int slidingPuzzle(vector<vector<int>>& board) {
  4.         // Get the moves where 0 can move.. idx->vector<int>.
  5.         vector<vector<int>> moves = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
  6.         string end = "123450";
  7.         unordered_map<string, bool> visited;
  8.        
  9.         // Init start string with distance 0.
  10.         string begin = "";
  11.         for(int i = 0; i < board.size(); i++) {
  12.             for(int j = 0; j < board[0].size(); j++) {
  13.                 begin += to_string(board[i][j]);
  14.             }
  15.         }
  16.        
  17.         // Init queue of <string, int> : <state, distance>
  18.         queue<pair<string, int>> q;
  19.         q.push({begin, 0});
  20.         visited[begin] = true;
  21.        
  22.         while(!q.empty()){
  23.             auto curr = q.front();
  24.             q.pop();
  25.             string current = curr.first;
  26.            
  27.             // Reached end, return the number of moves.
  28.             if(current == end) return curr.second;
  29.            
  30.             // Find index of 0 and find all possible next moves
  31.             int idx = current.find("0");
  32.             for(auto i: moves[idx]){
  33.                 string next = current;
  34.                 swap(next[idx], next[i]);
  35.                 // If next state not visited, push it in queue.
  36.                 if(!visited.count(next)){
  37.                     visited[next] = true;
  38.                     q.push({next, curr.second+1});
  39.                 }
  40.             }
  41.         }
  42.         // If not possible to reach end state;
  43.         return -1;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement