leetcode 37 解数独
z

编写一个程序,通过已填充的空格来解决数独问题。

一个数独的解法需遵循如下规则:

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 ‘.’ 表示。

image-20190713112916129

一个数独。

image-20190713112924952

答案被标成红色。

Note:

给定的数独序列只包含数字 1-9 和字符 ‘.’ 。
你可以假设给定的数独只有唯一解。
给定数独永远是 9x9 形式的。


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
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.

"""
def dfs(usedCol, usedRow, usedGrid, col, row):
if col == 9:
col = 0
row += 1
if row == 9:
print(board)
return True
if board[row][col] != '.':
if dfs(usedCol, usedRow, usedGrid, col + 1, row):
return True
else:
for i in range(9):
if not usedRow[row][i] and not usedCol[col][i] and not usedGrid[row // 3][col // 3][i]:
usedRow[row][i] = True
usedCol[col][i] = True
usedGrid[row // 3][col // 3][i] = True
board[row][col] = str(i + 1)
if dfs(usedCol, usedRow, usedGrid, col + 1, row):
return True
board[row][col] = '.'
usedRow[row][i] = False
usedCol[col][i] = False
usedGrid[row // 3][col // 3][i] = False
return False

usedCol = [[False] * 9 for i in range(9)]
usedRow = [[False] * 9 for i in range(9)]
usedGrid = [[[False] * 9 for i in range(3)] for j in range(3)]

for i in range(9):
for j in range(9):
if board[i][j] != '.':
num = ord(board[i][j]) - ord('1')
usedRow[i][num] = True
usedCol[j][num] = True
usedGrid[i // 3][j // 3][num] = True

dfs(usedCol, usedRow, usedGrid, 0, 0)