题意:八数码。
思路:IDA*+曼哈顿距离+判断是否有解。因为要用到IDA*搜索,所以我们搜索之前先判断一下是否有解。
判断的方法是学习一个大神的: 判断八数码问题是否有解
IDA*比起BFS的好处是空间复杂度极低,同时因为有剪枝,比起BFS降低了盲目性;比起A*的好处是不用去维护一个堆。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int MAXN = 400000;
//const int INF = 0x3f3f3f3f;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, -1, 0, 1};
int mov[1000];
int maxd;
char c;
struct State {
int s[9];
int pos;
} state;
int cal_pos(int pos, int i) {
int nx = pos/3+dx[i], ny = pos%3+dy[i];
if(nx<0 || nx>2 || ny<0 || ny>2) return -1;
return nx*3 + ny;
}
int cal_h() {
int ans = 0;
for(int i = 0; i < 9; i++) {
if(state.s[i] == 9) continue;
int x = (state.s[i]-1)/3, y = (state.s[i]-1)%3;
int nx = i/3, ny = i%3;
ans += abs(x-nx) + abs(y-ny);
}
return ans;
}
void init() {
if(c != 'x') state.s[0] = c - '0';
else {
state.s[0] = 9;
state.pos = 0;
}
for(int i = 1; i < 9; i++) {
cin >> c;
if(c == 'x') {
state.s[i] = 9;
state.pos = i;
}
else state.s[i] = c - '0';
}
}
bool dfs(int d, int last) {
if(d == maxd) {
if(!cal_h()) return true;
return false;
}
for(int i = 0; i < 4; i++) {
if(abs(i-last) == 2) continue;
int newpos = cal_pos(state.pos, i);
if(newpos<0) continue;
swap(state.s[state.pos], state.s[newpos]);
swap(state.pos, newpos);
if(d+cal_h() > maxd) {
swap(state.s[state.pos], state.s[newpos]);
swap(state.pos, newpos);
continue;
}
mov[d+1] = i;
if(dfs(d+1, i)) return true;
swap(state.s[state.pos], state.s[newpos]);
swap(state.pos, newpos);
}
return false;
}
void IDA_star() {
for(maxd = 0; ; maxd++) {
if(dfs(0, 100)) return;
}
}
void print_path(int dep) {
if(!dep) return;
print_path(dep-1);
if(!mov[dep]) printf("u");
else if(mov[dep]==1) printf("l");
else if(mov[dep]==2) printf("d");
else printf("r");
}
bool is_solvable() {
int cnt = 0;
for(int i = 0; i < 9; i++) {
if(state.s[i] == 9) continue;
for(int j = 0; j < i; j++) {
if(state.s[j] == 9) continue;
if(state.s[j] > state.s[i]) cnt++;
}
}
return !(cnt%2);
}
int main() {
//freopen("input.txt", "r", stdin);
while(cin >> c) {
init();
if(!is_solvable()) printf("unsolvable");
else {
IDA_star();
print_path(maxd);
}
puts("");
}
return 0;
}