【BZOJ1085】[SCOI2005]骑士精神

点我传送到题面

1085: [SCOI2005]骑士精神

Time Limit: 10 Sec  Memory Limit: 162 MB
Submit: 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

2
10110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100

Sample Output

7
-1

HINT

Source

[Submit][Status][Discuss]



第一眼看就是一个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;
}
posted @ 2017-04-01 08:07  Edward_Tsui  阅读(117)  评论(0编辑  收藏  举报