MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / exits_word

Function exits_word

backtracking/word_search.py:47–88  ·  view source on GitHub ↗

Return True if it's possible to search the word suffix starting from the word_index. >>> exits_word([["A"]], "B", 0, 0, 0, set()) False

(
    board: list[list[str]],
    word: str,
    row: int,
    column: int,
    word_index: int,
    visited_points_set: set[int],
)

Source from the content-addressed store, hash-verified

45
46
47def exits_word(
48 board: list[list[str]],
49 word: str,
50 row: int,
51 column: int,
52 word_index: int,
53 visited_points_set: set[int],
54) -> bool:
55 """
56 Return True if it's possible to search the word suffix
57 starting from the word_index.
58
59 >>> exits_word([["A"]], "B", 0, 0, 0, set())
60 False
61 """
62
63 if board[row][column] != word[word_index]:
64 return False
65
66 if word_index == len(word) - 1:
67 return True
68
69 traverts_directions = [(0, 1), (0, -1), (-1, 0), (1, 0)]
70 len_board = len(board)
71 len_board_column = len(board[0])
72 for direction in traverts_directions:
73 next_i = row + direction[0]
74 next_j = column + direction[1]
75 if not (0 <= next_i < len_board and 0 <= next_j < len_board_column):
76 continue
77
78 key = get_point_key(len_board, len_board_column, next_i, next_j)
79 if key in visited_points_set:
80 continue
81
82 visited_points_set.add(key)
83 if exits_word(board, word, next_i, next_j, word_index + 1, visited_points_set):
84 return True
85
86 visited_points_set.remove(key)
87
88 return False
89
90
91def word_exists(board: list[list[str]], word: str) -> bool:

Callers 1

word_existsFunction · 0.85

Calls 3

get_point_keyFunction · 0.85
addMethod · 0.45
removeMethod · 0.45

Tested by

no test coverage detected