Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
3
Indexable
Never
def helper_paths_n(n, board, words, current_path, paths):
    if len(current_path) > n:
        return

    last_cell = current_path[-1]
    last_row, last_col = last_cell

    # Define the eight possible directions
    directions = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)]

    if len(current_path) == n:
        word=""
        for tup in current_path:
            word+=board[tup[0]][tup[1]]
        if word in words:
            paths.append(current_path[:])  # Append a copy of the current_path
        return

    # Explore adjacent cells
    for r1, r2 in directions:
        new_row, new_col = last_row + r1, last_col + r2
        if 0 <= new_row < len(board) and 0 <= new_col < len(board[new_row]):
            new_cell = (new_row, new_col)
            if new_cell not in current_path:
                current_path.append(new_cell)  # Append the new_cell to current_path
                helper_paths_n(n, board, words, current_path, paths)
                current_path.pop()  # Remove the new_cell from current_path





def find_length_n_paths(n: int, board: Board, words: Iterable[str]) -> List[Path]:
    paths = []
    for row in range(len(board)):
        for col in range(len(board[row])):
            start_cell = (row, col)
            helper_paths_n(n, board, words, [start_cell], paths)

    return paths