注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
self.helper(board, 0)
def helper(self, board, num):
for i in range(num, 81):
row, col = i // 9, i % 9
if board[row][col] != ".":
continue
else:
for v in self.candidate(board, row, col): # all the possible numbers for that position
board[row][col] = v
if self.helper(board, i + 1): # for next position
return True
board[row][col] = "." # backtrack
return False
return True
def candidate(self, board, x, y): # all the possible numbers for that position
seen = set()
for i in range(9):
seen.add(board[x][i])
seen.add(board[i][y])
for i in range(3):
for j in range(3):
seen.add(board[x//3 + i][y//3 + j])
cans = set([str(i) for i in range(1, 10)])
return cans.difference(seen)
|