-
Notifications
You must be signed in to change notification settings - Fork 0
/
37.py
67 lines (57 loc) · 2.12 KB
/
37.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# 37. Sudoku Solver
class Solution(object):
# def isValid(self, board, row, col, c):
# for i in range(9):
# if board[row][i]==c:
# return False
# if board[i][col]==c:
# return False
# if board[row/3*3+col/3][i]==c:
# return False
# return True
def isValid(self, board, x, y):
# row
for i in range(9):
if i != x and board[i][y] == board[x][y]:
return False
# col
for j in range(9):
if j != y and board[x][j] == board[x][y]:
return False
# 3x3 box
x_st, y_st = 3 * (x / 3), 3 * (y / 3)
for i in range(x_st, x_st + 3):
for j in range(y_st, y_st + 3):
if (i != x or j != y) and board[i][j] == board[x][y]:
return False
return True
def solve(self, board):
for i in range(9):
for j in range(9):
if board[i][j]=='.':
for x in '123456789':
board[i][j] = x
if self.isValid(board, i, j) and self.solve(board):
return True
board[i][j]='.'
return False
return True
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
self.solve(board)
print board
if __name__ == '__main__':
solution = Solution()
board = [["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"]]
solution.solveSudoku(board)