Skip to content

Instantly share code, notes, and snippets.

@shiracamus
Created March 3, 2020 10:58
Show Gist options
  • Save shiracamus/05bea7340085f9af740daa5df0b8dca1 to your computer and use it in GitHub Desktop.
Save shiracamus/05bea7340085f9af740daa5df0b8dca1 to your computer and use it in GitHub Desktop.
board = """
| 45| 6| 3 |
| | 49|126|
| | | |
+---+---+---+
| 12| | 4|
|9 | 62| |
| 87| | 9|
+---+---+---+
| | | |
| | 95|687|
| 76| 3| 9 |
""".splitlines()
SPACE = 0
board = [[int(number) if number.isdigit() else SPACE
for number in row.replace('|', '')]
for row in board[1:4]+board[5:8]+board[9:12]]
def solve(board, row=0, col=0):
while board[row][col] != SPACE:
if col < 8:
col += 1
elif row < 8:
col = 0
row += 1
else:
return True
for number in candidate(board, row, col):
board[row][col] = number
if solve(board, row, col):
return True
board[row][col] = SPACE
return False
def candidate(board, row, col):
if board[row][col] != SPACE:
return []
row_numbers = board[row]
col_numbers = [board[r][col] for r in range(9)]
box_row = row - row % 3
box_col = col - col % 3
box_numbers = [board[r][c]
for r in range(box_row, box_row + 3)
for c in range(box_col, box_col + 3)]
conflict_numbers = row_numbers + col_numbers + box_numbers
return set(range(1, 10)) - set(conflict_numbers)
def main():
if solve(board):
for row in board:
print(*row)
else:
print("No answer")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment