From 928b034e9bca9667949e22b589ece1b6f0b7a4d0 Mon Sep 17 00:00:00 2001 From: Jijie LIU Date: Thu, 17 Jun 2021 17:27:30 +0200 Subject: [PATCH] =?UTF-8?q?update=2037.=20=E8=A7=A3=E6=95=B0=E7=8B=AC:=20?= =?UTF-8?q?=E6=8F=90=E4=BE=9Bpython3=20=E7=89=88=E6=9C=AC=EF=BC=8C?= =?UTF-8?q?=E7=AE=80=E5=8C=96isValid=EF=BC=8C=20=E6=8F=90=E9=AB=98?= =?UTF-8?q?=E5=9B=9E=E6=BA=AF=E5=87=BD=E6=95=B0=E7=9A=84=E5=8F=AF=E8=AF=BB?= =?UTF-8?q?=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0037.解数独.md | 53 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/0037.解数独.md b/problems/0037.解数独.md index 4eb60704..e43708b8 100644 --- a/problems/0037.解数独.md +++ b/problems/0037.解数独.md @@ -321,6 +321,59 @@ class Solution: backtrack(board) ``` +Python3: + +```python3 +class Solution: + def __init__(self) -> None: + self.board = [] + + def isValid(self, row: int, col: int, target: int) -> bool: + for idx in range(len(self.board)): + # 同列是否重复 + if self.board[idx][col] == str(target): + return False + # 同行是否重复 + if self.board[row][idx] == str(target): + return False + # 9宫格里是否重复 + box_row, box_col = (row // 3) * 3 + idx // 3, (col // 3) * 3 + idx % 3 + if self.board[box_row][box_col] == str(target): + return False + return True + + def getPlace(self) -> List[int]: + for row in range(len(self.board)): + for col in range(len(self.board)): + if self.board[row][col] == ".": + return [row, col] + return [-1, -1] + + def isSolved(self) -> bool: + row, col = self.getPlace() # 找个空位置 + + if row == -1 and col == -1: # 没有空位置,棋盘被填满的 + return True + + for i in range(1, 10): + if self.isValid(row, col, i): # 检查这个空位置放i,是否合适 + self.board[row][col] = str(i) # 放i + if self.isSolved(): # 合适,立刻返回, 填下一个空位置。 + return True + self.board[row][col] = "." # 不合适,回溯 + + return False # 空位置没法解决 + + def solveSudoku(self, board: List[List[str]]) -> None: + """ + Do not return anything, modify board in-place instead. + """ + if board is None or len(board) == 0: + return + self.board = board + self.isSolved() +``` + Go: Javascript: