骑士精神
题目背景:
分析:迭代加深搜索,每一次枚举走多少步能够到达,每一次搜索当前步数的可行解,判断是否到达最终目标位置,加入剪枝,如果中途发现当前的差异已经大于剩余步数,则表示这个状态不可行直接放弃即可。
Source:
/*
created by scarlyw
*/
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <cctype>
#include <vector>
#include <set>
#include <queue>
inline char read() {
static const int IN_LEN = 1024 * 1024;
static char buf[IN_LEN], *s, *t;
if (s == t) {
t = (s = buf) + fread(buf, 1, IN_LEN, stdin);
if (s == t) return -1;
}
return *s++;
}
///*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return ;
if (c == '-') iosig = true;
}
for (x = 0; isdigit(c); c = read())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int OUT_LEN = 1024 * 1024;
char obuf[OUT_LEN], *oh = obuf;
inline void write_char(char c) {
if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;
*oh++ = c;
}
template<class T>
inline void W(T x) {
static int buf[30], cnt;
if (x == 0) write_char('0');
else {
if (x < 0) write_char('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) write_char(buf[cnt--]);
}
}
inline void flush() {
fwrite(obuf, 1, oh - obuf, stdout);
}
/*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = getchar(), iosig = false; !isdigit(c); c = getchar())
if (c == '-') iosig = true;
for (x = 0; isdigit(c); c = getchar())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int ans[5][5] = {1, 1, 1, 1, 1,
0, 1, 1, 1, 1,
0, 0, 2, 1, 1,
0, 0, 0, 0, 1,
0, 0, 0, 0, 0};
int dx[8] = {1, 1, -1, -1, 2, 2, -2, -2};
int dy[8] = {2, -2, 2, -2, 1, -1, 1, -1};
int a[5][5], k, t;
bool flag;
inline bool check(int a[5][5]) {
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
if (a[i][j] != ans[i][j]) return false;
return true;
}
inline bool able(int a[5][5], int x) {
int cnt = 0;
for (int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
if (a[i][j] != ans[i][j]) cnt++;
return ((cnt + x) <= k);
}
inline void dfs(int cur, int a[5][5], int x, int y) {
if (cur == k) return (void)(flag = check(a));
if (flag) return ;
for (int i = 0; i < 8; ++i) {
int cx = x + dx[i], cy = y + dy[i];
if (cx < 0 || cx > 4 || cy < 0 || cy > 4) continue ;
std::swap(a[cx][cy], a[x][y]);
if (able(a, cur)) dfs(cur + 1, a, cx, cy);
std::swap(a[cx][cy], a[x][y]);
}
}
int main() {
scanf("%d", &t);
while (t--) {
static int x, y;
static char c[10];
for (int i = 0; i < 5; ++i) {
scanf("%s", c);
for (int j = 0; j < 5; ++j)
a[i][j] = ((c[j] == '*') ? (x = i, y = j, 2) : c[j] - '0');
}
for (k = 0; k <= 15; ++k) {
dfs(0, a, x, y);
if (flag) {
std::cout << k << '\n';
break ;
}
}
flag ? (flag = false) : (std::cout << "-1\n", flag);
}
return 0;
}