From 7a2ea78dbbe42fb938646961dc68b36ca20413f2 Mon Sep 17 00:00:00 2001 From: Kadambari Date: Mon, 6 Apr 2026 14:29:30 +0200 Subject: [PATCH 1/2] Added get_word_path function --- backtracking/word_search.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/backtracking/word_search.py b/backtracking/word_search.py index 8a9b2f1b5359..e7237c0908fe 100644 --- a/backtracking/word_search.py +++ b/backtracking/word_search.py @@ -87,6 +87,42 @@ def exits_word( return False +def get_word_path( + board: list[list[str]], word: str +) -> list[tuple[int, int]] | None: + rows, cols = len(board), len(board[0]) + + def backtrack(r, c, index, path, visited): + if board[r][c] != word[index]: + return None + + path.append((r, c)) + visited.add((r, c)) + + if index == len(word) - 1: + return path.copy() + + directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] + + for dr, dc in directions: + nr, nc = r + dr, c + dc + if 0 <= nr < rows and 0 <= nc < cols and (nr, nc) not in visited: + result = backtrack(nr, nc, index + 1, path, visited) + if result: + return result + + path.pop() + visited.remove((r, c)) + return None + + for i in range(rows): + for j in range(cols): + result = backtrack(i, j, 0, [], set()) + if result: + return result + + return None + def word_exists(board: list[list[str]], word: str) -> bool: """ From 174e2e4d8047e411cd2f5ca093f87328eb89dcfc Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 6 Apr 2026 12:33:53 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- backtracking/word_search.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/backtracking/word_search.py b/backtracking/word_search.py index e7237c0908fe..9bd33705af8f 100644 --- a/backtracking/word_search.py +++ b/backtracking/word_search.py @@ -87,9 +87,8 @@ def exits_word( return False -def get_word_path( - board: list[list[str]], word: str -) -> list[tuple[int, int]] | None: + +def get_word_path(board: list[list[str]], word: str) -> list[tuple[int, int]] | None: rows, cols = len(board), len(board[0]) def backtrack(r, c, index, path, visited):