Created
October 7, 2014 15:11
-
-
Save amikrop/506061bab17937fd4e8d to your computer and use it in GitHub Desktop.
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
def same_row(x, y, grid): | |
for j in xrange(9): | |
if j != y and grid[x][j] != '0': | |
yield grid[x][j] | |
def same_column(x, y, grid): | |
for i in xrange(9): | |
if i != x and grid[i][y] != '0': | |
yield grid[i][y] | |
def same_box(x, y, grid): | |
coords = x, y | |
candidates = [[], []] | |
for i in xrange(2): | |
if not coords[i] % 3: | |
candidates[i] = coords[i], coords[i] + 1, coords[i] + 2 | |
elif coords[i] % 3 == 1: | |
candidates[i] = coords[i] - 1, coords[i], coords[i] + 1 | |
else: | |
candidates[i] = coords[i] - 2, coords[i] - 1, coords[i] | |
for i in candidates[0]: | |
for j in candidates[1]: | |
if (i, j) != (x, y) and grid[i][j] != '0': | |
yield grid[i][j] | |
def valid(x, y, d, grid): | |
if d in same_row(x, y, grid) or d in same_column(x, y, grid) or d in same_box(x, y, grid): | |
return False | |
return True | |
def solve(grid, x, y): | |
if x == 9: | |
return True | |
next_x = x | |
next_y = y + 1 | |
if y == 8: | |
next_x = x + 1 | |
next_y = 0 | |
if grid[x][y] != '0': | |
return solve(grid, next_x, next_y) | |
for d in '123456789': | |
grid[x][y] = d | |
if valid(x, y, d, grid): | |
if solve(grid, next_x, next_y): | |
return True | |
grid[x][y] = '0' | |
return False | |
fp = open('sudoku.txt') | |
contents = fp.read() | |
fp.close() | |
total = 0 | |
for line in contents.splitlines(): | |
if line.startswith('G'): | |
grid = [[0 for x in xrange(9)] for y in xrange(9)] | |
i = 0 | |
else: | |
for j, d in enumerate(line): | |
grid[i][j] = d | |
i += 1 | |
if i == 9: | |
solve(grid, 0, 0) | |
total += int(grid[0][0]) * 100 + int(grid[0][1]) * 10 + int(grid[0][2]) | |
print total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment