Python | Leetcode Python题解之第37题解数独

题目:

题解:

class Solution:
    def solveSudoku(self, board: List[List[str]]) -> None:
        def dfs(pos: int):
            nonlocal valid
            if pos == len(spaces):
                valid = True
                return
            
            i, j = spaces[pos]
            for digit in range(9):
                if line[i][digit] == column[j][digit] == block[i // 3][j // 3][digit] == False:
                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True
                    board[i][j] = str(digit + 1)
                    dfs(pos + 1)
                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = False
                if valid:
                    return
            
        line = [[False] * 9 for _ in range(9)]
        column = [[False] * 9 for _ in range(9)]
        block = [[[False] * 9 for _a in range(3)] for _b in range(3)]
        valid = False
        spaces = list()

        for i in range(9):
            for j in range(9):
                if board[i][j] == ".":
                    spaces.append((i, j))
                else:
                    digit = int(board[i][j]) - 1
                    line[i][digit] = column[j][digit] = block[i // 3][j // 3][digit] = True

        dfs(0)

相关推荐

  1. 游戏(c++题解)

    2024-04-20 17:50:05       42 阅读
  2. [力扣题解]37. 解数

    2024-04-20 17:50:05       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-20 17:50:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-20 17:50:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-20 17:50:05       82 阅读
  4. Python语言-面向对象

    2024-04-20 17:50:05       91 阅读

热门阅读

  1. 几款AI语音克隆使用分享(未完成)

    2024-04-20 17:50:05       38 阅读
  2. play with serverless services (by quqi99)

    2024-04-20 17:50:05       38 阅读
  3. 数据结构-图

    2024-04-20 17:50:05       25 阅读
  4. 基于单片机的船舶柴油机冷却水温控制研究

    2024-04-20 17:50:05       34 阅读
  5. 数据结构8:队列

    2024-04-20 17:50:05       34 阅读
  6. 【c/c++】编写头文件

    2024-04-20 17:50:05       34 阅读
  7. 【PyTorch Lightning】.ckpt 是什么?里面有什么?

    2024-04-20 17:50:05       31 阅读
  8. 蓝队面试经验总结

    2024-04-20 17:50:05       38 阅读