LeetCode(力扣)37. 解数独Python

LeetCode37. 解数独

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/sudoku-solver/description/
LeetCode(力扣)37. 解数独Python_第1张图片

代码

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] != '.':
                    continue
                for k in range(1, 10):
                    if self.is_valid(i, j, k, board):
                        board[i][j] = str(k)
                        if self.backtracking(board): return True
                        board[i][j] = '.'
                return False
        return True

    def is_valid(self, row, col, val, board):
        for i in range(9):
            if board[row][i] == str(val):
                return False
        for i in range(9):  
            if board[i][col] == str(val):
                return False

        start_row = (row // 3) * 3
        start_col = (col // 3) * 3
        for i in range(start_row, start_row + 3):
            for j in range(start_col, start_col + 3):
                if board[i][j] == str(val):
                    return False
        return True
            

你可能感兴趣的:(leetcode,python,算法,职场和发展)