使用map存最小步数
使用string存储每次图的状态
string和二维数组之间可以转化
并且string也可以用swap交换字符
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
string _end = "12345678x";
queue<string> q;
unordered_map<string,int> step;
vector<vector<char>> string_to_char(string a){
vector<vector<char>> tmp;
for(int i = 0;i<a.size();i+=3){
vector<char> t;
for(int j = i;j<3+i;j++){
t.push_back(a[j]);
}
tmp.push_back(t);
}
return tmp;
}
int dx[] = {0,0,1,-1};
int dy[] = {1,-1,0,0};
pair<int ,int > getx(string a){
pair<int,int > r;
for(int i = 0;i<a.size();i++){
if(a[i]=='x'){
r.first = i/3;
r.second = i%3;
}
}
return r;
}
string char_to_string(vector<vector<char>> v){
string t="";
for(auto i:v){
for(auto j: i) t+=j;
}
return t;
}
void bfs(string begin){
q.push(begin);
vector<vector<char>> map_begin = string_to_char(begin);
step[begin] = 0;
while(!q.empty()){
string str = q.front();
q.pop();
pair<int,int> t = getx(str);
for(int i = 0;i<4;i++){
string tmp(str);
int cx = t.first+dx[i];
int cy = t.second+dy[i];
swap(tmp[cx*3+cy],tmp[t.first*3+t.second]);
if(cx>=0&&cx<3&&cy>=0&&cy<3&&step.find(tmp)==step.end())
{
step[tmp] = step[str] + 1;
if(tmp == _end) return;
q.push(tmp);
}
}
}
}
int main() {
char c;
string begin ="";
int x,y;
for(int i = 0;i<9;i++){
cin>>c;
begin+=c;
}
bfs(begin);
if(step.find(_end)!=step.end())
cout<<step[_end];
else
cout<<-1;
return 0;
}