Skip to content

Commit 7a2ea78

Browse files
Added get_word_path function
1 parent 840ca00 commit 7a2ea78

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

backtracking/word_search.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,42 @@ def exits_word(
8787

8888
return False
8989

90+
def get_word_path(
91+
board: list[list[str]], word: str
92+
) -> list[tuple[int, int]] | None:
93+
rows, cols = len(board), len(board[0])
94+
95+
def backtrack(r, c, index, path, visited):
96+
if board[r][c] != word[index]:
97+
return None
98+
99+
path.append((r, c))
100+
visited.add((r, c))
101+
102+
if index == len(word) - 1:
103+
return path.copy()
104+
105+
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
106+
107+
for dr, dc in directions:
108+
nr, nc = r + dr, c + dc
109+
if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in visited:
110+
result = backtrack(nr, nc, index + 1, path, visited)
111+
if result:
112+
return result
113+
114+
path.pop()
115+
visited.remove((r, c))
116+
return None
117+
118+
for i in range(rows):
119+
for j in range(cols):
120+
result = backtrack(i, j, 0, [], set())
121+
if result:
122+
return result
123+
124+
return None
125+
90126

91127
def word_exists(board: list[list[str]], word: str) -> bool:
92128
"""

0 commit comments

Comments
 (0)