Created
July 29, 2014 02:47
-
-
Save Bekt/f4f1040623baae3e9813 to your computer and use it in GitHub Desktop.
Given a 2d array, check if it is a valid sudoku solution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
def is_valid(board, n): | |
if not sanity_check(board, n): | |
return False | |
# Check horizontally and vertically. | |
for i in range(n): | |
if (not check_sub_board(board, n, 0, n, i, i + 1) | |
or not check_sub_board(board, n, i, i + 1, 0, n)): | |
return False | |
# Check sub-boards. | |
sub = 3 | |
for i in range(0, n, sub): | |
for j in range(0, n, sub): | |
if not check_sub_board(board, n, i, i + 3, j, j + 3): | |
return False | |
return True | |
def sanity_check(board, n): | |
if not board or len(board) != n: | |
return False | |
for row in board: | |
if len(row) != n: | |
return False | |
for cell in row: | |
if cell < 1 or cell > 9: | |
return False | |
return True | |
def check_sub_board(board, n, xs, xe, ys, ye): | |
s = set() | |
for i in range(xs, xe): | |
for j in range(ys, ye): | |
s.add(board[i][j]) | |
return len(s) == n; | |
def main(): | |
board =[[6, 2, 5, 9, 8, 7, 1, 4, 3], | |
[9, 7, 3, 4, 6, 1, 2, 8, 5], | |
[8, 1, 4, 5, 3, 2, 9, 7, 6], | |
[5, 8, 6, 3, 4, 9, 7, 2, 1], | |
[4, 9, 1, 7, 2, 6, 3, 5, 8], | |
[7, 3, 2, 8, 1, 5, 4, 6, 9], | |
[3, 4, 7, 1, 5, 8, 6, 9, 2], | |
[1, 6, 8, 2, 9, 4, 5, 3, 7], | |
[2, 5, 9, 6, 7, 3, 8, 1, 4]] | |
print(is_valid(board, 9)) # True | |
board =[[3, 2, 5, 9, 8, 7, 1, 4, 6], | |
[9, 7, 3, 4, 6, 1, 2, 8, 5], | |
[8, 1, 4, 5, 3, 2, 9, 7, 6], | |
[5, 8, 6, 3, 4, 9, 7, 2, 1], | |
[4, 9, 1, 7, 2, 6, 3, 5, 8], | |
[7, 3, 2, 8, 1, 5, 4, 6, 9], | |
[3, 4, 7, 1, 5, 8, 6, 9, 2], | |
[1, 6, 8, 2, 9, 4, 5, 3, 7], | |
[2, 5, 9, 6, 7, 3, 8, 1, 4]] | |
print(is_valid(board, 9)) # False | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment