class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board)
{
unordered_set<string> state ;
string start ;
int pos = 0 ;
for(int i = 0 ; i < 2 ; ++i)
{
for(int j = 0 ; j < 3 ; ++j)
{
if(board[i][j] == 0)
{
pos = i * 3 + j ;
}
start += to_string(board[i][j]) ;
}
}
return slidingPuzzle(start , pos , 0 , state) ;
}
int slidingPuzzle(string start , int pos , int n , unordered_set<string> state)
{
vector<int> dir = {-1 , 0 , 1 , 0 , -1} ;
int res = INT_MAX ;
for(int k = 0 ; k < 4 ; ++k)
{
int new_i = pos / 3 + dir[k] , new_j = pos % 3 + dir[k + 1] ;
if(new_i < 0 || new_i >= 2 || new_j < 0 || new_j >= 3) continue ;
int new_pos = new_i * 3 + new_j ;
swap(start[pos] , start[new_pos]) ;
if(start == target) return n + 1 ;
if(!state.count(start))
{
state.insert(start) ;
int tmp = slidingPuzzle(start , new_pos , n + 1 , state) ;
if(tmp != -1 ) res = min(res , tmp) ;
state.erase(start) ;
swap(start[pos] , start[new_pos]) ;
}
}
return res == INT_MAX ? -1 : res ;
}
private :
string target = "123450" ;
};
class Solution {
public:
int slidingPuzzle(vector<vector<int>>& board)
{
unordered_set<string> state ;
vector<int> dir = {-1 , 0 , 1 , 0 , -1} ;
string start ;
for(int i = 0 ; i < 2 ; i++)
for(int j = 0 ; j < 3 ; j++)
start += to_string(board[i][j]) ;
queue<string> q ;
q.push(start) ;
state.insert(start) ;
int res = 0 ;
if(start == target) return res ;
while(!q.empty())
{
res++ ;
for(int i = q.size() - 1 ; i >= 0 ; i--)
{
start = q.front() ;
q.pop() ;
int pos = start.find("0") ;
for(int i = 0 ; i < 4 ; ++i)
{
int new_i = pos / 3 + dir[i] , new_j = pos % 3 + dir[i + 1] ;
if(new_i < 0 || new_i >= 2 || new_j < 0 || new_j >= 3) continue ;
int new_pos = new_i * 3 + new_j ;
swap(start[pos] , start[new_pos]) ;
if(start == target) return res ;
if(state.empty() || !state.count(start))
{
state.insert(start) ;
q.push(start) ;
}
swap(start[pos] , start[new_pos]) ;
}
}
}
return -1 ;
}
private :
string target = "123450" ;
};