AcWing 845. 不要问 问就是莽
原题链接
中等
作者:
illusion_2
,
2020-03-25 17:45:19
,
所有人可见
,
阅读 648
#include <iostream>
#include <map>
#include <queue>
#include <cstdlib>
using namespace std;
typedef long long LL;
map<LL, LL> m;
//位移向量
int dir[4] = {-3, -1, 1, 3};
int main(){
int arr[9];
for(int i = 0; i < 9; ++i){
char ch;
cin >> ch;
if(ch == 'x'){
arr[i] = 9;
}else{
arr[i] = ch - '0';
}
}
bool flag = true;
for(int i = 0; i < 9; ++i){
if(i + 1 != arr[i]){
flag = false;
break;
}
}
if(flag){
cout << 0 << endl;
return 0;
}
queue<LL> q;
bool found = false;
LL num = 0;
for(int i = 0; i < 9; ++i){
num = num * 10 + arr[i];
}
q.push(num);
m[num] = 0;
while(!q.empty()){
int temp[9], idx = 0;
LL now = q.front();
LL tNow = now;
q.pop();
//分解
for(int i = 8; i >= 0; --i){
temp[i] = tNow % 10;
tNow /= 10;
//记录x的位置
if(temp[i] == 9){
idx = i;
}
}
//尝试移动
for(int i = 0; i < 4; ++i){
int newX = idx + dir[i];
if(newX == 2 && idx == 3){
continue;
}else if(newX == 5 && idx == 6){
continue;
}else if(newX == 3 && idx == 2){
continue;
}else if(newX == 6 && idx == 5){
continue;
}
if(newX >= 0 && newX < 9){
LL tn = 0;
for(int i = 0; i < 9; ++i){
if(i == newX){
tn = tn * 10 + 9;
}else if(i == idx){
tn = tn * 10 + temp[newX];
}else{
tn = tn * 10 + temp[i];
}
}
if(m.count(tn) == 0){
// cout << now << " -> " << tn << endl;
m[tn] = m[now] + 1;
q.push(tn);
if(tn == 123456789){
found = true;
break;
}
}
}
}
if(found){
break;
}
}
cout << (m[123456789] == 0 ? -1 : m[123456789])<< endl;
return 0;
}