MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

python3/Tries/find_all_words_on_a_board.py:28–46  ·  view source on GitHub ↗
(board: List[List[str]], r: int, c: int, node: TrieNode, res: List[str])

Source from the content-addressed store, hash-verified

26 return res
27
28def dfs(board: List[List[str]], r: int, c: int, node: TrieNode, res: List[str]) -> None:
29 # If the current node represents the end of a word, add the word to
30 # the result.
31 if node.word:
32 res.append(node.word)
33 # Ensure the current word is only added once.
34 node.word = None
35 temp = board[r][c]
36 # Mark the current cell as visited.
37 board[r][c] = '#'
38 # Explore all adjacent cells that correspond with a child of the
39 # current TrieNode.
40 dirs = [(-1, 0), (1, 0), (0, -1), (0, 1)]
41 for d in dirs:
42 next_r, next_c = r + d[0], c + d[1]
43 if (is_within_bounds(next_r, next_c, board) and board[next_r][next_c] in node.children):
44 dfs(board, next_r, next_c, node.children[board[next_r][next_c]], res)
45 # Backtrack by reverting the cell back to its original character.
46 board[r][c] = temp
47
48def is_within_bounds(r: int, c: int, board: List[str]) -> bool:
49 return 0 <= r < len(board) and 0 <= c < len(board[0])

Callers 1

Calls 1

is_within_boundsFunction · 0.70

Tested by

no test coverage detected