knakul853

Untitled

Jun 9th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. /*
  2. knakul853
  3. 6:44 pm
  4. Tuesday, 9 June 2020 (IST)
  5. */
  6. class Solution {
  7. public:
  8.     int slidingPuzzle(vector<vector<int>>& board) {
  9.         // 1 2 3
  10.         // 4 5 0
  11.         //123456
  12.        
  13.         vector<vector<int>>moves{{1, 3},{0, 2, 4}, {1, 5}, {0,4}, {3, 1, 5}, {2, 4}};
  14.        
  15.         string end = "123450";
  16.        
  17.         string start="";
  18.         for(auto v: board)
  19.         {
  20.             for(auto num : v)
  21.             {
  22.                 start += to_string(num);
  23.             }
  24.         }
  25.        
  26.         queue<string>q;
  27.         unordered_map<string, int>mp;
  28.         mp[start] = 1;
  29.         q.push( start );
  30.         int ans = 0;
  31.        
  32.         while( !q.empty() )
  33.         {
  34.             int sz = (int)q.size();
  35.             for( int i=0;i<sz;i++ )
  36.             {
  37.             auto node =  q.front();
  38.            
  39.             if(node == end ) return ans;
  40.             q.pop();
  41.            
  42.             int id = (int)node.find("0");
  43.              
  44.                 for( int num : moves[id] )
  45.                 {
  46.                     swap(node[ num ], node[ id ]);
  47.                     if(!mp.count(node))
  48.                     {
  49.                         mp[node] = 1;
  50.                         q.push( node );
  51.                     }
  52.                     swap(node[ num ], node[ id ]);
  53.                 }
  54.             }
  55.            
  56.             ans++;
  57.            
  58.         }
  59.        
  60.         return -1;
  61.        
  62.     }
  63. };
Add Comment
Please, Sign In to add comment