#๐Ÿ”’ shortest path using back tracking

4 messages ยท Page 1 of 1 (latest)

hollow viperBOT
#

@torpid fern

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

torpid fern
#

i have to find the shortest path using back tracking knowing start and end position and also a few nodes it has to visit and a few it has to avoid i can get it to visit the required nodes but it does not go to the end node

#
    rows, cols = len(grid), len(grid[0])
    visited = set()

    def is_valid_move(row, col):
        return 0 <= row < rows and 0 <= col < cols and grid[row][col] == 1

    def backtrack(row, col, path):
        if all(node in visited for node in nodes_to_visit):
            if (row, col) == end_node:
                return path + [end_node]
            return None

        visited.add((row, col))

        shortest = None
        for dr, dc in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            new_row, new_col = row + dr, col + dc
            if is_valid_move(new_row, new_col) and (new_row, new_col) not in visited:
                new_path = backtrack(new_row, new_col, path + [(row, col)])
                if new_path:
                    if shortest is None or len(new_path) < len(shortest):
                        shortest = new_path

        visited.remove((row, col))
        return shortest

    return backtrack(start_node[0], start_node[1], [])

# Example usage:
grid = [
    [1, 1, 0, 1, 1, 1],
    [1, 1, 1, 1, 0, 1],
    [1, 1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1, 1]
]

start_node = (0, 0)
end_node = (1, 0)
nodes_to_visit = {(1, 1), (2, 4)}

path = shortest_path(grid, start_node, end_node, nodes_to_visit)
if path:
    print("Shortest path:")
    for node in path:
        print(node)
else:
    print("No path found.") ```
hollow viperBOT
#

@torpid fern

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.