Skip to content

Add arrays/sudoku_solver.py #10623

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 6 commits into from
Oct 17, 2023
Merged
Changes from 4 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
41 changes: 41 additions & 0 deletions data_structures/arrays/sudoku_solver.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
n = 9

def isValid(row, col, ch):
row, col = int(row), int(col)

for i in range(9):
if board[i][col] == ch:
return False
if board[row][i] == ch:
return False

if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == ch:
return False

return True

def solve(row, col):
if row == n:
return True
if col == n:
return solve(row + 1, 0)

if board[row][col] == ".":
for i in range(1, 10):
if isValid(row, col, str(i)):
board[row][col] = str(i)

if solve(row, col + 1):
return True
else:
board[row][col] = "."
return False
else:
return solve(row, col + 1)

solve(0, 0)


# do upvote if it helps.