mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Remove redundent function in Backtracking Sudoku (#4499)
* Remove redundent function After reviewing this code, I've noticed that the `is_completed` function is a redundant operation. Increasing the number of loops required for each step of the sudoku solver. This should remove n² operations where n is the width of the grid. * Update sudoku.py Remove additional newline
This commit is contained in:
parent
b743e44259
commit
c824b90ead
@ -59,27 +59,6 @@ def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def is_completed(grid: Matrix) -> bool:
|
|
||||||
"""
|
|
||||||
This function checks if the puzzle is completed or not.
|
|
||||||
it is completed when all the cells are assigned with a non-zero number.
|
|
||||||
|
|
||||||
>>> is_completed([[0]])
|
|
||||||
False
|
|
||||||
>>> is_completed([[1]])
|
|
||||||
True
|
|
||||||
>>> is_completed([[1, 2], [0, 4]])
|
|
||||||
False
|
|
||||||
>>> is_completed([[1, 2], [3, 4]])
|
|
||||||
True
|
|
||||||
>>> is_completed(initial_grid)
|
|
||||||
False
|
|
||||||
>>> is_completed(no_solution)
|
|
||||||
False
|
|
||||||
"""
|
|
||||||
return all(all(cell != 0 for cell in row) for row in grid)
|
|
||||||
|
|
||||||
|
|
||||||
def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
|
def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
|
||||||
"""
|
"""
|
||||||
This function finds an empty location so that we can assign a number
|
This function finds an empty location so that we can assign a number
|
||||||
@ -111,12 +90,7 @@ def sudoku(grid: Matrix) -> Optional[Matrix]:
|
|||||||
>>> sudoku(no_solution) is None
|
>>> sudoku(no_solution) is None
|
||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
|
if location := find_empty_location(grid):
|
||||||
if is_completed(grid):
|
|
||||||
return grid
|
|
||||||
|
|
||||||
location = find_empty_location(grid)
|
|
||||||
if location is not None:
|
|
||||||
row, column = location
|
row, column = location
|
||||||
else:
|
else:
|
||||||
# If the location is ``None``, then the grid is solved.
|
# If the location is ``None``, then the grid is solved.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user