Good Morning!
I'm working on an algorithm to find paths between two given nodes (start and end), a graph (represented as it's adjacency list) and a list containing the current visited nodes. This is the code I've done in Python:
def find_path(graph, start, end, visited):
path = []
if graph[start][end] == 1:
return [start,end]
if start not in visited:
visited.append(start)
path.insert(0, start)
for neighbour in range(0, len(graph)):
if graph[start][neighbour] == 1 and neighbour not in visited:
path.extend(find_path(graph, neighbour, end, visited))
return path
I may have something wrong because given this:
visited = []
g1 = [[0, 1, 1, 0, 0],
[1, 0, 1, 1, 0],
[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 0]]
print(find_path(g1, 0, 4, visited))
assert find_path(g1, 0, 4, visited) in [[0, 2, 4], [0, 2, 1, 3, 4], [0, 1, 2, 4], [0, 1, 3, 4]]
This is the result I get: [0, 1, 2, 4, 3, 4, 2, 4] and of course an assertion error.
Why does it add each subpath?