BFS求最小步数
class Solution {
public:
/**
* @param board: the given board
* @return: the least number of moves required so that the state of the board is solved
*/
string vector2string(vector<vector<int>> v) {
string res(6, '0');
int j = 0;
for (int i = 0; i < 2; i++) {
for (int k = 0; k < 3; k++) {
res[j] = v[i][k] + '0';
j++;
}
}
return res;
}
vector<vector<int>> string2vector(string tar){
vector<vector<int>> v(2, vector<int>(3,0));
int j = 0;
for (int i = 0; i < 2; i++) {
for (int k = 0; k < 3; k++) {
v[i][k] = tar[j] - '0';
j++;
}
}
return v;
}
int slidingPuzzle(vector<vector<int>> &board) {
// write your code here
string target = "123450" , cur = vector2string(board);
vector<vector<int>> move = {{1,0},{0,1},{0,-1},{-1,0}};
unordered_set<string> s;
s.insert(cur);
queue<string> q;
q.push(cur);
int res = 0;
while (!q.empty()) {
res++;
int n = q.size();
while (n > 0) {
string temp = q.front();
q.pop();
if (temp == target)
return res-1;
vector<vector<int>> v = string2vector(temp);
int pos_x, pos_y;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
if (v[i][j] == 0) {
pos_x = i;
pos_y = j;
break;
}
}
}
for (int i = 0; i < 4; i++){
int new_pos_x = pos_x + move[i][0],
new_pos_y = pos_y + move[i][1];
if (new_pos_x >= 0 && new_pos_x <=1 && new_pos_y >= 0 && new_pos_y <= 2) {
vector<vector<int>> new_v = v;
swap(new_v[pos_x][pos_y], new_v[new_pos_x][new_pos_y]);
string str = vector2string(new_v);
if (s.count(str) == 0) {
q.push(str);
s.insert(str);
}
}
}
n--;
}
}
return -1;
}
};