Sudoku Killer(搜索)

Sudoku Killer

[link](Problem - 1426 (stdu.edu.cn))

题意

给你一道数独题,输出他的解。

题解

枚举需要填的位置,不断的填然后看是否成立即可。但是这样搜索的时间复杂度很高,有可能会被一些数据卡,考虑优化。

一般搜索优化可以考虑的有:

  1. 优化搜索顺序:尽量使得分支数量少,好剪枝
  2. 排除等效冗余:组合数,不重复
  3. 可行性剪枝:不符合条件的都砍掉
  4. 最优化剪枝:比当前结果大的都砍掉
  5. 记忆化搜索(DP)

我们考虑用二进制优化,分别用三个二进制数来表示行、列、方格里那些数可以填,当前位置可以填的就是 r o w & c o l & c e l l row \&col\& cell row&col&cell 。考虑优化搜索顺序,我们的递归搜索树一定是越瘦越好,所以我们选需要填的位置可选择最小的,当第一次搜索到以后就直接回溯。

恶心的输入输出,行末卡空格,输入可以用cin读然后遇到空格直接就停了。

Code

暴力

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<"#x"<<:<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 110, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1);
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
	e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
struct Node {
	int x, y;
}g[N];
char str[N];
bool ok = true;
int get(char c) {
	return (c - '0');
}
bool check(int u, int num) {
	int x = g[u].x, y = g[u].y;
	for (int i = 0; i < 9; i ++ ) 
		if (get(str[x * 9 + i]) == num || get(str[i * 9 + y]) == num) return false;
	x = x / 3 * 3, y = y / 3 * 3;
	for (int i = 0; i < 3; i ++ )
		for (int j = 0; j < 3; j ++ )
			if (get(str[(x + i) * 9 + (y + j)]) == num) return false;
	return true;
}
void dfs(int u) {
	if (u == k) {
		for (int i = 0, vis = 0; i < 9; i ++ )
			for (int j = 0; j < 9; j ++, vis ++)
				cout << str[vis] << (j == 8 ? '\n' : ' ');
		ok = true;
		return ;
	}
	if (ok) return ;
	for (int i = 1; i <= 9; i ++ ) 
		if (check(u, i)) {
			str[g[u].x * 9 + g[u].y] = '0' + i;
			dfs(u + 1);
			str[g[u].x * 9 + g[u].y] = '0';
		}
}
int main() {
	ios::sync_with_stdio(false), cin.tie(0);
	char c; int p = 0;
	while (cin >> c) {
		int cnt = 0; k = 0, ok = false;
		str[cnt ++] = c;
		if (c == '?') g[k].x = 0, g[k ++].y = 0;
		for (int i = 0; i < 9; i ++ )
			for (int j = 0; j < 9; j ++ ) {
				if (!i && !j) continue;
				cin >> c; str[cnt ++] = (c == '?' ? '0' : c);
				if (c == '?') 	g[k].x = i, g[k ++].y = j;				
			}
		if (p ++) cout << endl;
		dfs(0);
	}
	return 0;
}

优化

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>

#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#define x first
#define y second
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 9, M = 1 << N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8;
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int n, m; 
int ones[M], map[M];
int row[N], col[N], cell[3][3];
char str[100];
void init() {
	for (int i = 0; i < N; i ++ )
		row[i] = col[i] = (1 << N) - 1; // 初始化,每一个位置都可以填
		for (int i = 0; i < 3; i ++ )
			for (int j = 0; j < 3; j ++ )
				cell[i][j] = (1 << N) - 1; 
}
void draw(int x, int y, int t, bool is_set ) {
	if (is_set) str[x * N + y] = '1' + t; // 填数
	else        str[x * N + y] = '?'; // 删数
	int v = 1 << t; // 找到对应二进制位置 
	if (!is_set) v = -v; // 负负得正,逆操作 
	row[x] -= v;
	col[y] -= v;
	cell[x / 3][y / 3] -= v;
} 
int lowbit(int x) {
	return x & -x;
}
int get(int x, int y) {
	return row[x] & col[y] & cell[x / 3][y / 3];
}
bool dfs(int cnt) {
	if (!cnt) return true; // 递归终点
	int minv = 10;
	int x, y;
	// 优化搜索顺序 
	for (int i = 0; i < N; i ++ )
		for (int j = 0; j < N; j ++ )
			if (str[i * N + j] == '?') {
				int state = get(i, j); // 当前这个点可以填的数
				if (ones[state] < minv)  {
					minv = ones[state];
					x = i, y = j;
				}
			}
    	int state = get(x, y); // 找到可以填的最少的,这样搜索分支少
	for (int i = state; i; i -= lowbit(i)) { // 从前往后枚举可以填哪个数
		int t = map[lowbit(i)]; 
		draw(x, y, t, true);
		if (dfs(cnt - 1)) return true; // 当前分支可以填完,返回true
        draw(x, y, t, false); // 恢复现场
	}
	return false;
}

int main() {
	//ios::sync_with_stdio(false), cin.tie(0);
	for (int i = 0; i < N; i ++ ) map[1 << i] = i; // 这个数对应的是第几位,方便后面转化为数字 
	for (int i = 0; i < 1 << N; i ++ )
		for (int j = 0; j < N; j ++ )
			ones[i] += i >> j & 1; // 当前这个情况有多少个可以填的
	char c;
    int t = 0;
    while (cin >> c) {
        int p = 0;
        str[p++] = c;
		init();
		int cnt = 0;
        for (int i = 0; i < N; i ++ )
            for (int j = 0; j < N; j ++ ) {
                if (!i && !j) continue;
                cin >> c; str[p ++] = c;
            }
        // for (int i = 0, k = 0; i < N; i ++ ) {
        //      for (int j = 0; j < N; j ++, k ++ )
        //         cout << str[k];
        //     cout << endl;
        // }           
		for (int i = 0, k = 0; i < N; i ++ ) 
			for (int j = 0; j < N; j ++, k ++ )
				if (str[k] != '?') {
					int t = str[k] - '1'; // 二进制优化是[0, 8] 
					draw(i, j, t, true); // 把row col cell 初始化 
				}
				else cnt ++;
		dfs(cnt);    
        if (t ++) cout << endl;
		for (int i = 0, k = 0; i < N; i ++ ) {
			for (int j = 0; j < N; j ++, k ++ )
				cout << str[k] << (j != N - 1 ? ' ': '\n') ;		
        }    
	}
	return 0; 
}

[Link](166. 数独 - AcWing题库)

如果不剪枝做这道题,就会T。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值