LeetCode37. 解数独
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/sudoku-solver/description/
代码
class Solution:def solveSudoku(self, board: List[List[str]]) -> None:"""Do not return anything, modify board in-place instead."""self.backtracking(board)def backtracking(self, board):for i in range(len(board)):for j in range(len(board[0])):if board[i][j] != '.':continuefor k in range(1, 10):if self.is_valid(i, j, k, board):board[i][j] = str(k)if self.backtracking(board): return Trueboard[i][j] = '.'return Falsereturn Truedef is_valid(self, row, col, val, board):for i in range(9):if board[row][i] == str(val):return Falsefor i in range(9): if board[i][col] == str(val):return Falsestart_row = (row // 3) * 3start_col = (col // 3) * 3for i in range(start_row, start_row + 3):for j in range(start_col, start_col + 3):if board[i][j] == str(val):return Falsereturn True