1

I've to find all possible path between two nodes.

The given line represent edge present between two nodes. I can easily find one possible path but how to find remaining paths?

#edges representation:
see this image for reference

7 --> total edges

1-3

1-4

2-3

2-4

5-6

6-7

3-5

graph={}
n=int(input())
for i in range(n):
    l=list(map(int,input().split('-')))
    if l[0] not in graph:
        graph[l[0]]=[l[1]]
    else:
        graph[l[0]] += [l[1]]

def path(start,end,graph):
    que=[]
    que.append([start])
    while que:
        path=que.pop()

        if path[-1]==end:
            return path
        for adj_node in graph.get(path[-1],[]):
            new_path=list(path)
            new_path.append(adj_node)
            que.append(new_path)

print(path(1,6,graph))

Output: [1, 3, 5, 6]

abhi nav
  • 11
  • 1

1 Answers1

0

Use networkx:

# Python env: pip install networkx
# Anaconda: conda install networkx
import networkx as nx

edges = [(1, 3), (1, 4), (2, 3), (2, 4), (5, 6), (6, 7), (3, 5)]

G = nx.from_edgelist(edges)

paths = nx.all_simple_paths(G, 1, 6)

Output:

>>> list(paths)
[[1, 3, 5, 6],
 [1, 4, 2, 3, 5, 6]]
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thank you very much for the answer and quick reply, but can you please give any approach using bfs or dfs? it would help a lot to understand the transversal, anyway thank you once again for the answer. – abhi nav Feb 06 '22 at 09:04
  • Check https://stackoverflow.com/questions/12864004/tracing-and-returning-a-path-in-depth-first-search – Corralien Feb 06 '22 at 09:15