Skip to content

Commit 9cbb439

Browse files
Merge pull request #417 from EnzoSeason/leetcode-37
update 37. 解数独: 提供python3 版本,简化isValid, 提高回溯函数的可读性
2 parents 69ab3b8 + 928b034 commit 9cbb439

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

problems/0037.解数独.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,59 @@ class Solution:
321321
backtrack(board)
322322
```
323323

324+
Python3:
325+
326+
```python3
327+
class Solution:
328+
def __init__(self) -> None:
329+
self.board = []
330+
331+
def isValid(self, row: int, col: int, target: int) -> bool:
332+
for idx in range(len(self.board)):
333+
# 同列是否重复
334+
if self.board[idx][col] == str(target):
335+
return False
336+
# 同行是否重复
337+
if self.board[row][idx] == str(target):
338+
return False
339+
# 9宫格里是否重复
340+
box_row, box_col = (row // 3) * 3 + idx // 3, (col // 3) * 3 + idx % 3
341+
if self.board[box_row][box_col] == str(target):
342+
return False
343+
return True
344+
345+
def getPlace(self) -> List[int]:
346+
for row in range(len(self.board)):
347+
for col in range(len(self.board)):
348+
if self.board[row][col] == ".":
349+
return [row, col]
350+
return [-1, -1]
351+
352+
def isSolved(self) -> bool:
353+
row, col = self.getPlace() # 找个空位置
354+
355+
if row == -1 and col == -1: # 没有空位置,棋盘被填满的
356+
return True
357+
358+
for i in range(1, 10):
359+
if self.isValid(row, col, i): # 检查这个空位置放i,是否合适
360+
self.board[row][col] = str(i) # 放i
361+
if self.isSolved(): # 合适,立刻返回, 填下一个空位置。
362+
return True
363+
self.board[row][col] = "." # 不合适,回溯
364+
365+
return False # 空位置没法解决
366+
367+
def solveSudoku(self, board: List[List[str]]) -> None:
368+
"""
369+
Do not return anything, modify board in-place instead.
370+
"""
371+
if board is None or len(board) == 0:
372+
return
373+
self.board = board
374+
self.isSolved()
375+
```
376+
324377
Go:
325378

326379
Javascript:

0 commit comments

Comments
 (0)