POJ2676 Sudoku DFS

题目链接

http://poj.org/problem?id=2676

分析

每次找到可填数最少的位置先填,用二进制数来表示每行每列每个九宫格可填的数。

AC代码

#include 

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

const int maxn = 15;

int r[maxn], c[maxn], p[maxn], f[1 << 9], cnt[1 << 9];
char s[maxn][maxn];

inline int pos(int x, int y) {
	return x / 3 * 3 + y / 3;
}

inline void change(int x, int y, int k) {
	r[x] ^= 1 << k, c[y] ^= 1 << k, p[pos(x, y)] ^= 1 << k;
}

int dfs(int tot) {
	if (!tot) return 1;
	int mc = 10, x, y;
	for (int i = 0; i < 9; ++i)
		for (int j = 0; j < 9; ++j)
			if (s[i][j] == '0') {
				int num = r[i] & c[j] & p[pos(i, j)];
				if (cnt[num] < mc) mc = cnt[num], x = i, y = j;
			}
	int num = r[x] & c[y] & p[pos(x, y)];
	while (num) {
		int k = f[num & -num];
		num -= num & -num;
		s[x][y] = '1' + k;
		change(x, y, k);
		if (dfs(tot - 1)) return 1;
		s[x][y] = '0';
		change(x, y, k);
	}
	return 0;
}

int main() {
	for (int i = 0; i < 9; ++i) f[1 << i] = i;
	for (int i = 1; i < (1 << 9); ++i) cnt[i] = cnt[i - (i & -i)] + 1;
	int t = read();
	while (t--) {
		for (int i = 0; i < 9; ++i)
			r[i] = c[i] = p[i] = (1 << 9) - 1;
		int tot = 0;
		for (int i = 0; i < 9; ++i) {
			scanf("%s", s[i]);
			for (int j = 0; j < 9; ++j) {
				if (s[i][j] == '0') ++tot;
				else change(i, j, s[i][j] - '0' - 1);
			}
		}
		dfs(tot);
		for (int i = 0; i < 9; ++i) printf("%s\n", s[i]);
	}
	return 0;
}

你可能感兴趣的:(《算法竞赛进阶指南》)