hdu 2514 Another Eight Puzzle(DFS+回溯)



Filling G with 1 and D with 2 (or G with 2 and D with 1) is illegal since G and D are connected and 1 and 2 are consecutive .However ,filling A with 8 and B with 1 is legal since 8 and 1 are not consecutive .

In this problems,some circles are already filled,your tast is to fill the remaining circles to obtain a solution (if possivle).
 

Input

The first line contains a single integer T(1≤T≤10),the number of test cases. Each test case is a single line containing 8 integers 0~8,the numbers in circle A~H.0 indicates an empty circle.

 

Output

For each test case ,print the case number and the solution in the same format as the input . if there is no solution ,print “No answer”.If there more than one solution,print “Not unique”.
 

Sample Input

     
     
     
     
3 7 3 1 4 5 8 0 0 7 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
 

Sample Output

     
     
     
     
Case 1: 7 3 1 4 5 8 6 2 Case 2: Not unique Case 3: No answer
题目大意:八个城市,0~8  八个数值,要求填入的数值,相邻的不能连续,0为待定。

解题思路:DFS加回溯。

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;

#define N 10

int bo[N];
int tem[N];
int ti;

int judge(int num[])
{
	int f[17];
	memset(f, 0,sizeof(f));

	f[0] = num[0] - num[1];
	f[1] = num[0] - num[2];
	f[2] = num[0] - num[3];
	f[3] = num[1] - num[2];
	f[4] = num[1] - num[4];
	f[5] = num[1] - num[5];
	f[6] = num[2] - num[3];
	f[7] = num[2] - num[4];
	f[8] = num[2] - num[5];
	f[9] = num[2] - num[6];
	f[10] = num[3] - num[5];
	f[11] = num[3] - num[6];
	f[12] = num[4] - num[5];
	f[13] = num[4] - num[7];
	f[14] = num[5] - num[6];
	f[15] = num[5] - num[7];
	f[16] = num[6] - num[7];

	for (int i = 0; i < 17; i++)
		if (f[i] == -1 || f[i] == 1)
			return 0;
	return 1;}

void build(int num[], int k)
{
	if ( k != 0)
	{
		int i;
		for (i = 0; i < 8; i++)
			if (num[i] == 0)
				break;

		for (num[i] = 1; num[i] < 9; num[i]++)
			if (bo[num[i]])
				continue;
			else
			{
				bo[num[i]] = 1;
				build(num, k - 1);
				bo[num[i]] = 0;
			}
		num[i] = 0;
	}
	else
	{
		if (judge(num))
		{
			ti++;

			if (ti == 1)
				for (int i = 0; i < 8; i++)
					tem[i] = num[i];
		}
	}
}

int main()
{
	int num[N];

	int k;

	cin >> k;

	for (int j = 1; j <= k; j++)
	{
		// Init
		memset(num, 0, sizeof(num));
		memset(bo, 0, sizeof(bo));
		memset(tem, 0,sizeof(tem));
		ti = 0;
		int cnt = 0;

		// Read.
		for (int i = 0; i < 8; i++)
		{
			cin >> num[i];
			if (num[i])
			{
				bo[num[i]] = 1;
				cnt++;
			}
		}

		build(num, 8 - cnt);

		cout << "Case " << j << ":";

		if (ti == 1)
		{
			for (int i = 0; i < 8; i++)
				cout << " " << tem[i];
			cout << endl;
		}
		else if (ti > 1)
			cout << " Not unique" << endl;
		else if (ti == 0)
			cout << " No answer" << endl;
	}
	return 0;}

你可能感兴趣的:(hdu 2514 Another Eight Puzzle(DFS+回溯))