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.