天天看点

uva 167(暴力求解)

题意:八皇后的题,要求在8*8的棋盘上摆放8个皇后,这些皇后不同排,不同列,不在同一个斜线上,不同的是棋盘的每个位置有值,找出一种摆放方式使所有值的和最大,将和输出。

题解:递归。

#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
const int N = 8;

int mat[N][N], pos[N], ans; 

void init() {
	memset(pos, -1, sizeof(pos));
	ans = 0;
}

bool judge(int x, int y) {
	for (int i = 0; i < x; i++)
		if (pos[i] == y || abs(y - pos[i]) == abs(x - i))
			return false;
	return true;
}

void dfs(int cur, int count) {
	if (cur >= N) {
		if (count > ans)
			ans = count;
		return;
	}
	for (int i = 0; i < N; i++) {
		if (judge(cur, i)) {
			pos[cur] = i;
			dfs(cur + 1, count + mat[cur][i]);
		}
	}
}

int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		init();
		for (int i = 0; i < N; i++)
			for (int j = 0; j < N; j++)
				scanf("%d", &mat[i][j]);
		dfs(0, 0);
		printf("%5d\n", ans);
	}
	return 0;
}