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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。