update 37

This commit is contained in:
sangge-rockpi 2024-01-24 14:12:09 +08:00
parent eeef56d627
commit cf0b925c41

37
leetcode/37.py Normal file
View File

@ -0,0 +1,37 @@
# Sudoku Solver
class Solution:
def solveSudoku(self, board: list[list[int]]) -> None:
def isValid(board, row, col, num):
# Check if the number is in the current row
for x in range(9):
if board[row][x] == num:
return False
if board[x][col] == num:
return False
startRow, startCol = 3 * (row // 3), 3 * (col // 3)
for i in range(3):
for j in range(3):
if board[startRow + i][startCol + j] == num:
return False
return True
def solve(board):
for i in range(9):
for j in range(9):
if broad[i][j] == ".":
# Try all numbers for empty cell
for num in map(str, range(1, 10)):
if isValid(board, i, j, num):
board[i][j] = num
if solve(board):
return True
board[i][j] = "."
return False
return False
solve(board)