75. Valid Sudoku
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
board = [
[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]]TrueExample 2
board = [
[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]]FalseConstraints
boardhas 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).
- Keep a set of the digits seen so far in each row, each column and each box: 27 sets. A digit already in one of its three sets is a repeat.
- The cell at row
r, columncis in the box named(r // 3, c // 3): rows 0 to 2 give 0, rows 3 to 5 give 1, and so on. A dictionary from that pair to a set works well. - Skip the 0s.
r // 3 + c // 3is not a box name: boxes (0, 1) and (1, 0) would both get 1.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.