Sudoku Solver
LeetCode 37 · कठिन · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Backtracking over empty cells with a validity check.
मैंने Sudoku Solver (LeetCode 37) ऐसे हल किया — Constraint Satisfaction पैटर्न का एक कठिन प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Find the first empty cell and try digits 1–9 that don't clash with its row, column or 3×3 box. Place one and recurse; if the rest of the board can't be solved, undo it and try the next digit.
Approach
- 1
Scan for an empty cell.
- 2
Try each digit that is valid for its row, column and box.
- 3
Recurse; on failure, reset the cell.
- 4
No digit works → return False; no empty cell → solved.
मैंने कैसे हल किया
BacktrackingPythonexponential worst case
class Solution:
def solveSudoku(self, board):
def isValid(row, col, k, board):
for i in range(9):
if board[row][i] == k:
return False
if board[i][col] == k:
return False
if board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == k:
return False
return True
def solve(board):
for row in range(9):
for col in range(9):
if board[row][col] == ".":
for k in range(1, 10):
charK = str(k)
if isValid(row, col, charK, board):
board[row][col] = charK
if solve(board):
return True
else:
board[row][col] = "."
return False
return True
solve(board)Sudoku Solver — अक्सर पूछे जाने वाले प्रश्न
Sudoku Solver के पीछे intuition क्या है?
Find the first empty cell and try digits 1–9 that don't clash with its row, column or 3×3 box. Place one and recurse; if the rest of the board can't be solved, undo it and try the next digit.
Sudoku Solver (LeetCode 37) कैसे हल करें?
1. Scan for an empty cell. 2. Try each digit that is valid for its row, column and box. 3. Recurse; on failure, reset the cell. 4. No digit works → return False; no empty cell → solved.
Sudoku Solver की time और space complexity क्या है?
Time: O(9^m) for m empty cells। Space: O(m) recursion। (Accepted approach: Backtracking।)
Sudoku Solver में आम गलतियाँ क्या हैं?
The box index is 3·(row//3) + i//3, 3·(col//3) + i%3.