8皇后问题

8皇后问题太经典了,各种算法书解释回溯都用这个例子,下面是求解8皇后问题的代码:


#include <stdio.h>

static int count;

#define QUEEN_NUMBER 8
#define NO_QUEEN -1
#define TRUE 1
#define FALSE 0

#define ABS(x) ((x)>0?(x):(-(x)))

int conflict(int *queen, int pos)
{
	int i;
	for (i = 0; i < pos; i++) {
		if ((queen[i] == queen[pos]) || ABS((queen[i] - queen[pos])) == ABS(i - pos)) return TRUE;
	}
	return FALSE;
}

void try_next(int *queen, int pos)
{
	if (pos == QUEEN_NUMBER) 
	{
		count++;
		return;
	}
	int i;
	for (i = 0; i < QUEEN_NUMBER; i++) {
		queen[pos] = i;
		if (!conflict(queen, pos))
		{
			try_next(queen, pos + 1);
		}
	}
}

void foo(void)
{
	count = 0;
	int queen[QUEEN_NUMBER];
	int i;
	for (i = 0; i < QUEEN_NUMBER; i++) {
		queen[i] = NO_QUEEN;
	}
	try_next(queen, 0);
	printf("count = %d\n", count);
}

int main(int argc, const char *argv[])
{
	foo();
	return 0;
}

运行结果是8皇后问题共有92个解。

你可能感兴趣的:(算法,conflict)