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.