Question

Simple question: G is a directed graph with edges

a->b
a->c
c->d

It is stored in a Python dictionary

G={'a':['b','c'], c:['d']}

I want the path between a and d, the path between d and a, the path between b and d etc.

Was it helpful?

Solution

Straight from Guido van Rossum to you:

import collections
import itertools as IT

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

G={'a':['b','c'], 'c':['d']}

for node1, node2 in IT.combinations(list('abcd'), 2):
    print('{} -> {}: {}'.format(node1, node2, find_shortest_path(G, node1, node2)))

yields

a -> b: ['a', 'b']
a -> c: ['a', 'c']
a -> d: ['a', 'c', 'd']
b -> c: None
b -> d: None
c -> d: ['c', 'd']

You might also be interested in the networkx, igraph or graph-tool packages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top