简体   繁体   中英

Finding all paths in graph Python

I have adjacency matrix of some graph. I know nothing about how this graph looks like, it depends from starts conditions. It could be directed or undirected, cyclic, etc. So, I need to find all paths between all vertices.

Graph example

For example, in this particullar graph we have

2 0 3
2 1 3
2 0 1 3
0 2 1 3
0 1 3
1 3

I know about DFS or BFS, but don't know how to implement them in this task.

Let's say you've defined the adjacency matrix for this graph as

adj_matrix = [[0, 1, 1, 1],
              [0, 0, 0, 1],
              [1, 1, 0, 0],
              [0, 0, 0, 0]]

in that case, a recursive depth-first search for every path would work like this:

def iter_paths(adj, min_length=2, path=None):
    # different paths for starting and recurring
    # you could use two different methods, the first calling the second and 
    #   the second calling itself, if you wanted
    if not path:
        for start_node in range(len(adj)):
            yield from iter_paths(adj, min_length, [start_node])
    else:
        # yield a path as soon as we first encounter it
        if len(path) >= min_length:
            yield path
        # if we encounter a cycle (current location has been visited before)
        # then don't continue to recur
        if path[-1] in path[:-1]:  
            return
        # search for all paths forward from the current node, recursively
        current_node = path[-1]
        for next_node in range(len(adj[current_node])):
            if adj[current_node][next_node] == 1:
                yield from iter_paths(adj, min_length, path + [next_node])

print(list(iter_paths(adj_matrix)))

This produces the following list of paths:

[[0, 1],
 [0, 1, 3],
 [0, 2],
 [0, 2, 0],
 [0, 2, 1],
 [0, 2, 1, 3],
 [0, 3],
 [1, 3],
 [2, 0],
 [2, 0, 1],
 [2, 0, 1, 3],
 [2, 0, 2],
 [2, 0, 3],
 [2, 1],
 [2, 1, 3]]

A breadth-first algorithm would be very similar to a depth-first algorithm - except that, instead of using recursion, it would essentially keep a running list of path s that have been visited, and when a depth-first algorithm would call itself the breadth-first algorithm would simply add the new path to the list. It would iterate in a while loop until it reached the end of that list, then return the full list.

This only changes the order in which we examine nodes, in this case - you'll note that the depth-first search arranges them "alphabetically", whereas a breadth-first search would arrange them in ascending order of length.

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