Skip to content

37. Sudoku Solver

题目

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.
Related Topics
  • 数组
  • 哈希表
  • 回溯
  • 矩阵

  • 👍 1944
  • 👎 0
  • 思路

    N 皇后问题的扩展,需要先遍历棋盘获取已知条件

    • 已存放的数字,空置的位置
    • 将存放数字存入对应的 Col Row 哈希表中
    • 空置位置存入到 blank 数组中
    • 进行回溯操作

    注意棋盘上的数字是 char 类型,不是 int 类型

    解法

    python
    class Solution:
        def solveSudoku(self, board: List[List[str]]) -> None:
            GRID = 9
            col_map = {i: set() for i in range(GRID)}
            row_map = {i: set() for i in range(GRID)}
            box_map = {i: set() for i in range(GRID)}
            blank = []
    
            for row in range(GRID):
                for col in range(GRID):
                    if board[row][col] != '.':
                        b = (row // 3) * 3 + (col // 3)
                        col_map[col].add(board[row][col])
                        row_map[row].add(board[row][col])
                        box_map[b].add(board[row][col])
                    else:
                        blank.append([row, col])
    
            def backtrack(start):
                if start == len(blank):
                    return True
    
                row, col = blank[start]
                box_index = (row // 3) * 3 + (col // 3)
    
                for ch in map(str, range(1, 10)):
                    if ch in row_map[row] or ch in col_map[col] or ch in box_map[box_index]:
                        continue
                    board[row][col] = ch
                    col_map[col].add(board[row][col])
                    row_map[row].add(board[row][col])
                    box_map[box_index].add(board[row][col])
                    if backtrack(start + 1):
                        return True
                    col_map[col].remove(board[row][col])
                    row_map[row].remove(board[row][col])
                    box_map[box_index].remove(board[row][col])
                    board[row][col] = '.'
                return False
    
            backtrack(0)

    复杂度分析

    • 时间复杂度 O(9N)
      • N 为棋盘空位
    • 空间复杂度 O(N)