Algorithm to simplify/reduce graph

2.4k views Asked by At

Is there an algorithm that shortens paths (and removes nodes) based on edge cost? I can't put it into words too well so I hope these images sum it up well enough:

I need to get from this...

...to this

1

There are 1 answers

0
netword On BEST ANSWER

Are you looking for something out-of-the box or for algorithmic ideas on how to implement this yourself? I can help you with the latter.

What you want to do is called contraction of vertices which have exactly 2 neighbours, i.e. that have degree 2.

For implementing this, do the following:

while exists vertex v with degree 2:
    - remove v and the 2 outgoing edges
    - add a new edge between the neighbours of v
    - the weight of the new edge is the sum of the weights of the deleted edge

That is, if you have the following part of the graph: u ---2--- v ---5--- w and apply the contraction, you end up with u ---7--- w.

Just doing this iteratively until no vertex wit degree 2 remains will transform the graph in the first picture into the graph in your second picture.

The exact implementation details will, of course, depend on which data structure you use to represent your graph in Python (or any other language that is being used).