HDU 5547 Sudoku (暴力)

题意:数独。

析:由于只是4*4,完全可以暴力,要注意一下一些条件,比如2*2的小方格也得是1234

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std; typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 10 + 10;
const int mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
char s[maxn][maxn];
int a[maxn][maxn]; bool judge(int r, int c, int x){
int cnt = 0;
for(int i = 0; i < 4; ++i)
if(a[r][i] == x) ++cnt;
if(cnt > 0) return false;
cnt = 0;
for(int i = 0; i < 4; ++i)
if(a[i][c] == x) ++cnt;
return cnt < 1;
} bool solve(){
set<int> sets;
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 2; ++j)
sets.insert(a[i][j]);
if(sets.size() != 4) return false;
sets.clear();
for(int i = 2; i < 4; ++i)
for(int j = 2; j < 4; ++j)
sets.insert(a[i][j]);
if(sets.size() != 4) return false;
sets.clear();
for(int i = 2; i < 4; ++i)
for(int j = 0; j < 2; ++j)
sets.insert(a[i][j]);
if(sets.size() != 4) return false;
sets.clear();
for(int i = 0; i < 2; ++i)
for(int j = 2; j < 4; ++j)
sets.insert(a[i][j]);
if(sets.size() != 4) return false;
return true;
} bool dfs(int r, int c){
if(a[r][c]){
if(r == 3 && c == 3) return solve();
return c == 3 ? dfs(r+1, 0) : dfs(r, c+1);
}
for(int i = 1; i < 5; ++i) if(judge(r, c, i)){
a[r][c] = i;
int rr = r, cc = c;
if(r == 3 && c == 3){
if(solve()) return true;
a[r][c] = 0;
continue;
}
if(c == 3) ++rr, cc = 0;
else ++cc;
if(dfs(rr, cc)) return true;
a[r][c] = 0;
}
return false;
} int main(){
int T; cin >> T;
for(int kase = 1; kase <= T; ++kase){
for(int i = 0; i < 4; ++i) scanf("%s", s+i);
memset(a, 0, sizeof a);
for(int i = 0; i < 4; ++i)
for(int j = 0; j < 4; ++j)
if(s[i][j] != '*') a[i][j] = s[i][j] - '0';
dfs(0, 0);
printf("Case #%d:\n", kase);
for(int i = 0; i < 4; ++i, printf("\n"))
for(int j = 0; j < 4; ++j)
printf("%d", a[i][j]);
}
return 0;
}

  

上一篇:Spring注入对象(3)


下一篇:MSBuild的简单介绍与使用