1085: [SCOI2005]騎士精神
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2175 Solved: 1245
[Submit][Status][Discuss]
Description
在一個5×5的棋盤上有12個白色的騎士和12個黑色的騎士, 且有一個空位。在任何時候一個騎士都能按照騎
士的走法(它可以走到和它橫座標相差爲1,縱座標相差爲2或者橫座標相差爲2,縱座標相差爲1的格子)移動到空
位上。 給定一個初始的棋盤,怎樣才能經過移動變成如下目標棋盤: 爲了體現出騎士精神,他們必須以最少的步
數完成任務。
Input
第一行有一個正整數T(T<=10),表示一共有N組數據。接下來有T個5×5的矩陣,0表示白色騎士,1表示黑色騎
士,*表示空位。兩組數據之間沒有空行。
Output
對於每組數據都輸出一行。如果能在15步以內(包括15步)到達目標狀態,則輸出步數,否則輸出-1。
Sample Input
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
Sample Output
-1
HINT
Source
第一眼看就是一個Dfs。但是畢竟是一個省選題啊,而且交上dfs一看就不能滿分。所以在搜答案的時候就用啓發式搜索優化一下,思想就是基本的啓發式搜索,然後就像最短路一樣,如果發現答案劣於最優,那麼就停止繼續迭代。嗯,就這樣。搜索思想就是非常簡單的跳馬dfs。
#include <cstdlib>
#include <cstring>
#include <iostream>
int T, k;
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}
};
const int xx[8] = {1, 1, -1, -1, 2, 2, -2, -2};
const int yy[8] = {2, -2, 2, -2, 1, -1, 1, -1};
bool flag = false;
bool judge(int a[5][5])
{
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (ans[i][j] != a[i][j])
return false;
return true;
}
int eva(int a[5][5], const int s)
{
int v = 0;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
if (a[i][j] != ans[i][j])
{
v++;
if (v + s > k)
return false;
}
return true;
}
void Search(const int s, int a[5][5], const int x, const int y)
{
if (s == k)
{
if (judge(a))
flag = 1;
return;
}
if (flag)
return;
for (int i = 0; i < 8; i++)
{
int nowx = x + xx[i],
nowy = y + yy[i];
if (nowx < 0 || nowx > 4 || nowy < 0 || nowy > 4)
continue;
std::swap(a[x][y], a[nowx][nowy]);
if (eva(a, s))
Search(s + 1, a, nowx, nowy);
std::swap(a[x][y], a[nowx][nowy]);
}
}
int main(int argc, char ** argv)
{
std::ios_base::sync_with_stdio(false);
int T;
std::cin >> T;
while (T--)
{
int a[5][5] = { 0 };
int x, y;
std::memset(a, 0, sizeof a);
for (int i = 0; i < 5; i++)
{
char ch[10];
std::cin >> ch;
for (int j = 0; j < 5; j++)
if (ch[j] == '*')
{
a[i][j] = 2;
x = i;
y = j;
}
else
a[i][j] = ch[j] - '0';
}
for (k = 1; k <= 15; k++)
{
Search(0, a, x, y);
if (flag)
{
std::cout << k << std::endl;
break;
}
}
if (!flag)
std::cout << "-1\n";
else
flag = false;
}
#ifdef __EDWARD_TSUI_EDIT
std::system("pause");
#endif
return 0;
}