150强访谈简单

有效数独

“有效数独”问题的详细指南和 Python 实现。

问题陈述

简单

确定 9 x 9 数独板是否有效。仅需要根据以下规则验证填充的单元格:

1. 每行必须包含数字1-9,且不能重复。

2. 每列必须包含数字1-9,且不能重复。

3. 网格的九个 3 x 3 子框中的每一个都必须包含数字 1-9,且不能重复。

注意:数独板(部分填充)可能有效,但不一定可解。仅需要验证填充的单元格。

编写一个函数 isValidSudoku(board: List[List[str]]) -> bool

约束条件
  • board.length == 9
  • board[i].length == 9
  • board[i][j] is a digit 1-9 or '.'

示例

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
True
Explanation

No row, column, or 3x3 sub-box contains a duplicate digit.

Example 2
Input
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"]]
Output
False
Explanation

The digit 8 appears twice in the first column (rows 0 and 3) and twice in the top-left 3x3 sub-box.

Need a Hint?
考虑使用数组和哈希特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。