Skip to content

Instantly share code, notes, and snippets.

@hnh12358
Created September 27, 2010 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnh12358/598786 to your computer and use it in GitHub Desktop.
Save hnh12358/598786 to your computer and use it in GitHub Desktop.
function [Result ResultSudoku] = ResolveSudoku(InputSudoku)
A = [1 2 3 4 5 6 7 8 9];
B = [1 2 3 4 4 5 5 6 6 7 7 7 8 8 8 9 9 9];
C = [1 2 2 3 3 3 4 5 5 6 6 6 7 8 8 9 9 9];
f = @(x) sum(sum(power(2,x))) / 1022;
g = @(m,r,c) [m(3*r-2,3*c-2:3*c) m(3*r-1,3*c-2:3*c) m(3*r,3*c-2:3*c)];
j = @(m,r,c) g(m,sum(B == r),sum(B == c));
h = @(m,r,c) intersect(intersect(setdiff(A,m(r,:)),setdiff(A,m(:,c))),setdiff(A,j(m,r,c)));
function [R RS] = Resolve(IS,ESC)
if ESC == 0
for n = 1:9
r = sum(B == n); l = sum(C == n);
if sum([f(IS(n,:)) f(IS(:,n)) f(IS(3*r-2:3*r,3*l-2:3*l))]) ~= 3
R = 0; return;
end
end
RS = IS; R = 1;
else
a = 1; [rs, cs] = find(IS == 0);
while a ~= 0
a = 0;
for n = 1:ESC
D = h(IS,rs(n),cs(n));
if length(D) == 1
IS(rs(n),cs(n)) = D(1);
a = a + 1;
end
end
[rs, cs] = find(IS == 0); ESC = length(rs);
end
if ESC == 0
R = 1; RS = IS;
else
D = h(IS,rs(1),cs(1));
for n = 1:length(D)
IS(rs(1),cs(1)) = D(n);
[R RS] = Resolve(IS,ESC - 1);
if R == 1
return
end
end
R = 0; IS(rs(1),cs(1)) = 0; RS = IS; return
end
end
end
function R = IsSudokuCandidate(IS)
R = 1;
for n = 1:9
r = sum(B == n); l = sum(C == n);
P = [IS(n,:) IS(:,n)' [IS(3*r-2,3*l-2) IS(3*r-1,3*l-1) IS(3*r,3*l)]];
for i = 1:3
for j = 1:9
if sum( P(i) == A(j)) > 1
R = 0; return
end
end
end
end
end
if IsSudokuCandidate(InputSudoku) == 0
Result = 0; ResultSudoku = InputSudoku;
return
end
[Result ResultSudoku] = Resolve(InputSudoku,length(find(InputSudoku == 0)));
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment