📜  算法测验| Sudo放置:设置1 |问题2(1)

📅  最后修改于: 2023-12-03 15:27:26.373000             🧑  作者: Mango

算法测验 | Sudo放置:设置1 | 问题2

在这个算法测验中,我们将介绍Sudo放置问题的第二个问题。Sudo是一种逻辑推理和数学技巧的测验,旨在测试你的解决问题的能力和思维能力。

问题描述

给定一个9x9的数独矩阵,实现一个函数来验证它是否是有效的。数独矩阵仅包含数字1-9和字符'.',分别代表已知数字和未知数字。每一行,每一列和每个九宫格内的数字不能重复。

例如,

sudoku_example.png

上图是一个满足数独解法的矩阵。

一个有效的数独(部分已被填充)不一定是可解的。唯一的要求是,填入数字时不能有任何行,列或九宫格内有重复数字。

函数接口定义如下:

def isValidSudoku(board: List[List[str]]) -> bool:
    pass
示例1

输入:

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"]
]

输出: True

示例2

输入:

board = [
  ["8","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"]
]

输出: False

思路

本题可以通过三种情况的判断来得出答案:

  1. 每一行不能有重复的数字;
  2. 每一列不能有重复的数字;
  3. 每一个3x3宫格内不能有重复的数字。

因此,我们需要使用三个哈希表来分别存储行、列和九宫格内的数字。遍历数独矩阵时,我们同时更新三个哈希表,然后检查所得到的数字是否在哈希表中已存在。如果存在,则说明数独矩阵非法。

代码实现
from typing import List

def isValidSudoku(board: List[List[str]]) -> bool:
    # 初始化三个哈希表
    row_dict = [{} for _ in range(9)]
    col_dict = [{} for _ in range(9)]
    box_dict = [{} for _ in range(9)]
    
    # 遍历数独矩阵
    for i in range(9):
        for j in range(9):
            # 获取当前单元格的数字
            num = board[i][j]
            if num != '.':
                # 获取当前单元格所在的九宫格序列
                box_index = (i // 3) * 3 + j // 3
                # 如果数字已存在于哈希表中,则数独非法
                if num in row_dict[i] or num in col_dict[j] or num in box_dict[box_index]:
                    return False
                # 更新哈希表
                row_dict[i][num] = 1
                col_dict[j][num] = 1
                box_dict[box_index][num] = 1
    # 数独合法
    return True

以上是基本的数独判断方法,如果您有更好的想法,欢迎加入讨论!