Skip to content

Instantly share code, notes, and snippets.

@erning
Created June 19, 2012 10:37
Show Gist options
  • Save erning/2953457 to your computer and use it in GitHub Desktop.
Save erning/2953457 to your computer and use it in GitHub Desktop.
判断数独的棋盘是否符合规则
int validate(int *pieces) {
int sc[] = {0,0,0,0,0,0,0,0,0};
int sr[] = {0,0,0,0,0,0,0,0,0};
int sb[] = {0,0,0,0,0,0,0,0,0};
int n;
for (n = 0; n < 81; n++) {
int x = pieces[n];
if (x == 0) continue;
if (x < 1 || x > 9) return 0;
int c = n % 9; int r = n / 9; int b = c / 3 + r / 3 * 3;
x = 1 << (x - 1);
if (sc[c] & x || sr[r] & x || sb[b] & x) {
return 0;
}
sc[c] |= x; sr[r] |= x; sb[b] |= x;
}
return 1;
}
<?php
function validate($pieces) {
$sc = array(0,0,0,0,0,0,0,0,0);
$sr = array(0,0,0,0,0,0,0,0,0);
$sb = array(0,0,0,0,0,0,0,0,0);
for ($n = 0; $n < 81; $n++) {
$x = $pieces[$n];
if ($x == 0) {
continue;
}
if ($x < 1 || $x > 9) {
return false;
}
$c = $n % 9;
$r = (int)($n / 9);
$b = (int)($c / 3) + (int)($r / 3) * 3;
$x = 1 << ($x - 1);
if ($sc[$c] & $x || $sr[$r] & $x || $sb[$b] & $x) {
return false;
}
$sc[$c] |= $x; $sr[$r] |= $x; $sb[$b] |= $x;
}
return True;
}
def validate(pieces):
if len(pieces) != 81:
return False
col = lambda n : n % 9
row = lambda n : n / 9
blk = lambda n : col(n) / 3 + row(n) / 3 * 3
sc = [set() for i in xrange(9)]
sr = [set() for i in xrange(9)]
sb = [set() for i in xrange(9)]
n = -1
for x in pieces:
n += 1
if x == 0:
continue
if x < 1 or x > 9:
return False
c, r, b = col(n), row(n), blk(n)
if x in sc[c] or x in sr[r] or x in sb[b]:
return False
sc[c].add(x)
sr[r].add(x)
sb[b].add(x)
return True
@erning
Copy link
Author

erning commented Jun 19, 2012

输入参数是包含81个0..9元素的数组

import sudoku

p  = [0,0,8,0,1,0,0,0,9]
p += [6,0,1,0,9,0,3,2,0]
p += [0,4,0,0,3,7,0,0,5]
p += [0,3,5,0,0,8,2,0,0]
p += [0,0,2,6,5,0,8,0,0]
p += [0,0,4,0,0,1,7,5,0]
p += [5,0,0,3,4,0,0,8,0]
p += [0,9,7,0,8,0,5,0,6]
p += [1,0,0,0,6,0,9,0,0]
print sudoku.validate(p)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment