Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 79 · Grid Search / Backtracking DFS

Word Search

LeetCode 79 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Grid DFS with a path-visited set.

మధ్యస్థంArrayStringBacktrackingDepth-First SearchMatrix
LeetCode లో తెరవండి ↗

నేను Word Search (LeetCode 79) ను ఇలా పరిష్కరించాను — Grid Search / Backtracking DFS ప్యాటర్న్‌లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Start a DFS from every cell matching the first letter. Each step moves to a neighbour that matches the next letter and hasn't been used on the current path; un-mark the cell when backtracking.

Approach

  1. 1

    dfs(index, row, col): whole word matched → True.

  2. 2

    Out of bounds, wrong letter or already on the path → False.

  3. 3

    Mark, try four directions, unmark.

నేను ఎలా పరిష్కరించాను

Backtracking DFSPythonO(mn·3^L) time
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        m = len(board)
        n = len(board[0])
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        def dfs(index,row,col,visited):
            if index==len(word):
                return True
            if row<0 or row>=m or col<0 or col>=n:
                return False
            if board[row][col]!=word[index]:
                return False
            if (row,col) in visited:
                return False
            visited.add((row,col))
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if dfs(index+1,nrow,ncol,visited):
                        return True
            visited.remove((row,col))
            return False
        
        for i in range(m):
            for j in range(n):
                visited = set()
                if dfs(0,i,j,visited):
                    return True
        return False
స్టెప్-త్రూ లోడ్ అవుతోంది…

Word Search — తరచూ అడిగే ప్రశ్నలు

Word Search వెనుక ఉన్న intuition ఏమిటి?

Start a DFS from every cell matching the first letter. Each step moves to a neighbour that matches the next letter and hasn't been used on the current path; un-mark the cell when backtracking.

Word Search (LeetCode 79) ను ఎలా పరిష్కరించాలి?

1. dfs(index, row, col): whole word matched → True. 2. Out of bounds, wrong letter or already on the path → False. 3. Mark, try four directions, unmark.

Word Search యొక్క time, space complexity ఎంత?

Time: O(m · n · 3^L). Space: O(L). (Accepted approach: Backtracking DFS.)

Word Search లో సాధారణ పొరపాట్లు ఏమిటి?

Un-mark on the way back so other paths can reuse the cell.