简体   繁体   中英

How to find all simple paths possible in given graph?

I've to find all possible path between two nodes.<\/strong>

I can easily find one possible path but how to find remaining paths?


see this image for reference<\/a>

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))

Use networkx<\/code> :

# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM