Q
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
Example
![这里写图片描述]()
A sudoku puzzle…
![这里写图片描述]()
…and its solution numbers marked in red.
AC
class Solution:
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def solveSudoku(self, board):
def isValid(board, x, y):
for i in xrange(9):
if i != x and board[i][y] == board[x][y]:
return False
for j in xrange(9):
if j != y and board[x][j] == board[x][y]:
return False
i = 3 * (x / 3)
while i < 3 * (x / 3 + 1):
j = 3 * (y / 3)
while j < 3 * (y / 3 + 1):
if (i != x or j != y) and board[i][j] == board[x][y]:
return False
j += 1
i += 1
return True
def solver(board):
for i in xrange(len(board)):
for j in xrange(len(board[0])):
if(board[i][j] == '.'):
for k in xrange(9):
board[i][j] = chr(ord('1') + k)
if isValid(board, i, j) and solver(board):
return True
board[i][j] = '.'
return False
return True
solver(board)
if __name__ == '__main__':
board = [[".",".","9","7","4","8",".",".","."],
["7",".",".",".",".",".",".",".","."],
[".","2",".","1",".","9",".",".","."],
[".",".","7",".",".",".","2","4","."],
[".","6","4",".","1",".","5","9","."],
[".","9","8",".",".",".","3",".","."],
[".",".",".","8",".","3",".","2","."],
[".",".",".",".",".",".",".",".","6"],
[".",".",".","2","7","5","9",".","."]]
Solution().solveSudoku(board)
assert board == [["5","1","9","7","4","8","6","3","2"],
["7","8","3","6","5","2","4","1","9"],
["4","2","6","1","3","9","8","7","5"],
["3","5","7","9","8","6","2","4","1"],
["2","6","4","3","1","7","5","9","8"],
["1","9","8","5","2","4","3","6","7"],
["9","7","5","8","6","3","1","2","4"],
["8","3","2","4","9","1","7","5","6"],
["6","4","1","2","7","5","9","8","3"]]
作者:JNingWei 发表于2017/11/14 8:40:31
原文链接