Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 37 · Constraint Satisfaction

Sudoku Solver

LeetCode 37 · కఠినం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Backtracking over empty cells with a validity check.

కఠినంArrayHash TableBacktrackingMatrixAlgorithm X
LeetCode లో తెరవండి ↗

నేను 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. 1

    Scan for an empty cell.

  2. 2

    Try each digit that is valid for its row, column and box.

  3. 3

    Recurse; on failure, reset the cell.

  4. 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.