50 XP

75. Valid Sudoku

Intermediate sets grids

A Sudoku grid has 9 rows and 9 columns, split into nine 3x3 boxes. In a finished puzzle each row, each column and each box holds the digits 1 to 9 once each.

Write a function is_valid_sudoku(board) that takes a grid that may be only partly filled, as a list of 9 rows of 9 whole numbers, with 0 for an empty cell. Return True if no digit appears twice in any row, any column or any of the nine boxes, and False otherwise.

  • Only the filled cells count: any number of 0s is fine.
  • You don't need to check that the puzzle can be finished, only that the digits already there break no rule.
  • The boxes are the fixed 3x3 blocks: rows 0 to 2 with columns 0 to 2, rows 0 to 2 with columns 3 to 5, and so on.

Example 1

Inputboard = [ [5, 0, 0, 8, 0, 4, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 8, 6], [0, 8, 4, 0, 0, 0, 0, 0, 5], [3, 4, 0, 0, 0, 0, 0, 0, 7], [0, 0, 0, 0, 3, 0, 6, 0, 8], [8, 2, 0, 0, 7, 0, 0, 0, 0], [1, 0, 0, 0, 0, 3, 8, 0, 0], [0, 9, 0, 0, 1, 0, 3, 0, 0], [4, 6, 3, 0, 0, 0, 0, 0, 0]]
OutputTrue
ExplanationNo digit repeats anywhere.

Example 2

Inputboard = [ [5, 0, 0, 8, 0, 4, 0, 6, 0], [0, 0, 0, 0, 0, 0, 4, 8, 6], [0, 8, 4, 0, 0, 0, 0, 0, 5], [3, 4, 0, 0, 0, 0, 0, 0, 7], [0, 0, 0, 0, 3, 0, 6, 0, 8], [8, 2, 0, 0, 7, 0, 0, 0, 0], [1, 0, 0, 0, 0, 3, 8, 0, 0], [0, 9, 0, 0, 1, 0, 3, 0, 0], [4, 6, 3, 0, 0, 0, 0, 0, 0]]
OutputFalse
ExplanationThe top-right box has two 6s; its rows and columns are fine.

Constraints

  • board has 9 rows of 9 whole numbers, each from 0 to 9.

Submit also runs 7 more tests you can't see.

Practises Sets (lesson 12).

Code
def is_valid_sudoku(board):
    """Check that no filled-in digit breaks the rules.

    board: list of 9 rows of 9 ints, 0 for an empty cell
    Returns: bool, True if no digit repeats in a row, a
        column or a 3x3 box
    """
    # Write your code here
    pass