其他分享
首页 > 其他分享> > [LeetCode] 37. Sudoku Solver_Hard tag: BackTracking

[LeetCode] 37. Sudoku Solver_Hard tag: BackTracking

作者:互联网

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:

 

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).

 

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

 

标签:Sudoku,return,Solver,Hard,solution,range,board,must,row
来源: https://www.cnblogs.com/Johnsonxiong/p/14869580.html