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.