Skip to content

Added validate sudoku board function #9881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Oct 14, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions graphs/deep_clone_graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""
LeetCode 133. Clone Graph
https://leetcode.com/problems/clone-graph/

Given a reference of a node in a connected undirected graph.

Return a deep copy (clone) of the graph.

Each node in the graph contains a value (int) and a list (List[Node]) of its
neighbors.
"""
from dataclasses import dataclass


@dataclass
class Node:
value: int = 0
neighbors: list["Node"] | None = None

def __post_init__(self) -> None:
"""
>>> Node(3).neighbors
[]
"""
self.neighbors = self.neighbors or []

def __hash__(self) -> int:
"""
>>> hash(Node(3)) != 0
True
"""
return id(self)


def clone_graph(node: Node | None) -> Node | None:
"""
This function returns a clone of a connected undirected graph.
>>> clone_graph(Node(1))
Node(value=1, neighbors=[])
>>> clone_graph(Node(1, [Node(2)]))
Node(value=1, neighbors=[Node(value=2, neighbors=[])])
>>> clone_graph(None) is None
True
"""
if not node:
return None

originals_to_clones = {} # map nodes to clones

stack = [node]

while stack:
original = stack.pop()

if original in originals_to_clones:
continue

originals_to_clones[original] = Node(original.value)

stack.extend(original.neighbors or [])

for original, clone in originals_to_clones.items():
for neighbor in original.neighbors or []:
cloned_neighbor = originals_to_clones[neighbor]

if not clone.neighbors:
clone.neighbors = []

clone.neighbors.append(cloned_neighbor)

return originals_to_clones[node]


if __name__ == "__main__":
import doctest

doctest.testmod()
99 changes: 99 additions & 0 deletions matrix/validate_sudoku_board.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""
LeetCode 36. Valid Sudoku
https://leetcode.com/problems/valid-sudoku/
https://en.wikipedia.org/wiki/Sudoku

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be
validated according to the following rules:

- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9
without repetition.

Note:

A Sudoku board (partially filled) could be valid but is not necessarily
solvable.

Only the filled cells need to be validated according to the mentioned rules.
"""

from collections import defaultdict

NUM_ROWS = 9
NUM_COLS = 9
EMPTY_CELL = "."
IS_VALID = True
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use NUM_SQUARES instead of NUM_ROWS and NUM_ROWS.
Lets True and False in a boolean function.

Suggested change
NUM_ROWS = 9
NUM_COLS = 9
EMPTY_CELL = "."
IS_VALID = True
NUM_SQUARES = 9
EMPTY_CELL = "."



def is_valid_sudoku_board(sudoku_board: list[list[str]]) -> bool:
"""
This function validates (but does not solve) a sudoku board.
The board may be valid but unsolvable.

>>> is_valid_sudoku_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
>>> is_valid_sudoku_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
>>> is_valid_sudoku_board([["1", "2", "3", "4", "5", "6", "7", "8", "9"]])
Traceback (most recent call last):
...
Exception: Number of rows must be 9.
>>> is_valid_sudoku_board([["1"], ["2"], ["3"], ["4"], ["5"], ["6"], ["7"], ["8"], ["9"]])
Traceback (most recent call last):
...
Exception: Number of columns must be 9.
"""
if len(sudoku_board) != NUM_ROWS:
raise Exception("Number of rows must be 9.")

for row in sudoku_board:
if len(row) != NUM_COLS:
raise Exception("Number of columns must be 9.")
Copy link
Member

@cclauss cclauss Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if len(sudoku_board) != NUM_ROWS:
raise Exception("Number of rows must be 9.")
for row in sudoku_board:
if len(row) != NUM_COLS:
raise Exception("Number of columns must be 9.")
if len(sudoku_board) != NUM_SQUARES or any(
len(row) != NUM_SQUARES for row in sudoku_board
):
raise ValueError(f"Sudoku boards must be {NUM_SQUARES}x{NUM_SQUARES} squares.")


row_values = defaultdict(set) # maps each row to a set
col_values = defaultdict(set) # maps each col to a set
box_values = defaultdict(set) # maps each 3x3 box to a set

for row in range(NUM_ROWS):
for col in range(NUM_COLS):
value = sudoku_board[row][col]

if value == EMPTY_CELL:
continue

box = (row // 3, col // 3)

if (
value in row_values[row]
or value in col_values[col]
or value in box_values[box]
):
return not IS_VALID

row_values[row].add(value)
col_values[col].add(value)
box_values[box].add(value)

return IS_VALID