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.