简体   繁体   中英

Finding the Path of all Edges on a Graph

I'm trying to get the path on a graph which covers all edges, and traverses them only once. This means there will only be two "end" points - which will have an odd-number of attached nodes. These end points would either have one connecting edge, or be part of a loop and have 3 connections.

So in the simple case below I need to traverse the nodes in this order 1-2-3-4-5 (or 5-4-3-2-1):

简单的

In the more complicated case below the path would be 1-2-3-4-2 (or 1-2-4-3-2):

 - 图形

Below is also a valid graph, with 2 end-points: 1-2-4-3-2-5

复杂的

I've tried to find the name of an algorithm to solve this, and thought it was the "Chinese Postman Problem", but implementing this based on code at https://github.com/rkistner/chinese-postman/blob/master/postman.py didn't provide the results I expected.

The Eulerian path looks almost what is needed, but the networkx implementation will only work for closed (looped) networks.

I also looked at a Hamiltonian Path - and tried the networkx algorithm - but the graph types were not supported.

Ideally I'd like to use Python and networkx to implement this, and there may be a simple solution that is already part of the library, but I can't seem to find it.

You're looking for Eulerian Path that visits every edge exactly once. You can use Fleury's algorithm to generate the path. Fleury's algorithm has O(E^2) time complexity, if you need more efficient algorithm check Hierholzer's algorithm which is O(E) instead.

There is also an unmerged pull request for the networkx library that implements this. The source is easy to use.

(For networkx 1.11 the .edge has to be replaced with .edge_iter ).

This is known as the Eulerian Path of a graph. It has now been added to NetworkX as eulerian_path() .

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