AcWing 845. 八数码
原题链接
中等
作者:
依普昔侬
,
2020-03-29 23:52:25
,
所有人可见
,
阅读 681
#include<iostream>
#include<cstring>
#include<queue>
#include<unordered_map>
using namespace std;
string s;
int dx[4] = {1, -1, 0 , 0};
int dy[4] = {0, 0, -1, 1};
unordered_map<string, int> cnt;
int bfs(){
queue<string> q;
q.push(s);
cnt[s] = 0; // map可以用[]创建新内容;
string end = "12345678x";
while(q.size()){
auto t = q.front();
q.pop();
if(t == end) return cnt[end];
int distance = cnt[t];
int k = t.find('x');
for(int i = 0; i < 4; i++){
int x = k/3 + dx[i]; //一维转二维
int y = k%3 + dy[i];
if(x >= 0 && x < 3 && y >= 0 && y < 3){
int newk = x*3 + y;
swap(t[k], t[newk]);
//cout<< t << endl ;
if(!cnt.count(t)){
q.push(t);
cnt[t] = distance + 1;
}
swap(t[k], t[newk]);
}
}
}
return -1;
}
int main(){
char c; //先读入字符,然后在拼接给s;
for(int i = 0; i < 9; i++) {
cin>> c;
s += c;
}
//cout<<s<<endl;
cout<< bfs() ;
return 0;
}