Word Search
LeetCode 79 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Grid DFS with a path-visited set.
मैंने 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
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.
मैंने कैसे हल किया
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 FalseWord 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.