代码改变世界

[LeetCode] 37. Sudoku Solver_Hard tag: BackTracking

2021-06-10 06:52  Johnson_强生仔仔  阅读(38)  评论(0编辑  收藏  举报

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

The '.' character indicates empty cells.

 

Example 1:

Input: board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
Output: [["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]
Explanation: The input board is shown above and the only valid solution is shown below:

 

Constraints:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit or '.'.
  • It is guaranteed that the input board has only one solution.

 

Idea: 这个题目是在[LeetCode] 36. Valid Sudoku_Medium tag: Array的基础上加入了backtracking, 去将1 - 9放到空的,也就是有'.'的地方,然后不停的去弄, 每次要看行,列及相应的小正方形中有没有相应的数字, 如果有的话,那就continue, 直到所有的空都被填满, 否则的话就backtrack. 这里参考[LeetCode] 系统刷题7_Array & numbers & string中的对于每个小正方形里面的index要用newRow =  (row //3) * 3 + k //3, newCol =  (col //3) * 3 + k %3 for k in range(9).

 

Update on 08/16/2023. use n * n space to improve the time complexity. 

 

Code:

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        def backtrack(board):
            for i in range(9):
                for j in range(9):
                    if board[i][j] != '.':
                        continue
                    for c in "123456789":
                        if not self.isValid(board, i, j, c):
                            continue
                        board[i][j] = c
                        if backtrack(board):
                            return True
                        board[i][j] = '.'
                    return False
            return True
        helper(board)

    def isValid(self, board, i, j, c):
        for k in range(9):
            row = i //3 * 3 + k//3
            col = j //3 * 3 + k%3
            if c in [board[i][k], board[k][j], board[row][col]]:
                return False
        return True

 

improve the time complexity:

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        self.board = board
        self.rb = [[False] * 9 for _ in range(9)]
        self.cb = [[False] * 9 for _ in range(9)]
        self.ceb = [[False] * 9 for _ in range(9)]
        self.initial()
        self.backtrack()
        
    

    def backtrack(self):
        for r in range(9):
            for c in range(9):
                if self.board[r][c] != '.':
                    continue
                for each in "123456789":
                    if self.isValid(r, c, each):
                        self.board[r][c] = each
                        if self.backtrack():
                            return True
                        self.board[r][c] = '.'
                        index = int(each) - 1
                        cei = r //3 * 3 + c //3
                        self.rb[r][index] = False
                        self.cb[c][index] = False
                        self.ceb[cei][index] = False
                return False
        return True





    def initial(self):
        for r in range(9):
            for c in range(9):
                if self.board[r][c] != '.':
                    val = self.board[r][c]
                    index = int(val) - 1
                    cei = r //3 * 3 + c //3
                    self.rb[r][index] = True
                    self.cb[c][index] = True
                    self.ceb[cei][index] = True


    def isValid(self, r, c, val):
        index = int(val) - 1
        cei = r //3 * 3 + c //3
        if True in [self.rb[r][index], self.cb[c][index], self.ceb[cei][index] ]:
            return False
        self.rb[r][index] = True
        self.cb[c][index] = True
        self.ceb[cei][index] = True
        return True