Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for diameter of graph?

If you have a graph, and need to find the diameter of it (which is the maximum distance between two nodes), how can you do it in O(log v * (v + e)) complexity.

Wikipedia says you can do this using Dijkstra's algorithm with a binary heap. But I don't understand how this works. Can someone explain please?

Or show a pseudocode?

like image 995
omega Avatar asked Mar 26 '13 20:03

omega


People also ask

What is the algorithm to find the diameter of a graph?

The diameter of a graph is the largest distance between any pair of vertices, i.e. maxu,v d(u, v). The best known algorithm for finding the diameter exactly is by running an algorithm for APSP and returning the largest distance.

What is the diameter of a weighted graph?

The diameter of an edge-weighted graph (G,w) is the maximum distance be- tween two vertices: diam(G) := max{distG,w(u,v) | u ∈ V(G),v ∈ V(G)}.

How do you find the diameter of a graph in C++?

On the page Distance_(graph_theory) there are the following sentences: "To find the diameter of a graph, first find the shortest path between each pair of vertices. The greatest length of any of these paths is the diameter of the graph."


1 Answers

I know I'm a year late to the thread, but I don't believe any of these answers are correct. OP mentioned in the comments that the edges are unweighted; in this case, the best algorithm runs in O(nω log n) time (where ω is the exponent for matrix multiplication; currently upper bounded at 2.373 by Virginia Williams).

The algorithm exploits the following property of unweighted graphs. Let A be the adjacency matrix of the graph with an added self-loop for each node. Then (Ak)ij is nonzero iff d(i, j) ≤ k. We can use this fact to find the graph diameter by computing log n values of Ak.

Here's how the algorithm works: let A be the adjacency matrix of the graph with an added self loop for each node. Set M0 = A. While Mk contains at least one zero, compute Mk+1 = Mk2.

Eventually, you find a matrix MK with all nonzero entries. We know that K ≤ log n by the property discussed above; therefore, we have performed matrix multiplication only O(log n) times so far. We can now continue by binary searching between MK = A2K and MK-1 = A2K-1. Set B = MK-1 as follows.

Set DIAMETER = 2k-1. For i = (K-2 ... 0), perform the following test:

Multiply B by Mi and check the resulting matrix for zeroes. If we find any zeroes, then set B to this matrix product, and add 2i to DIAMETER. Otherwise, do nothing.

Finally, return DIAMETER.

As a minor implementation detail, it might be necessary to set all nonzero entries in a matrix to 1 after each matrix multiplication is performed, so that the values don't get too large and unwieldy to write down in a small amount of time.

like image 134
GMB Avatar answered Sep 30 '22 16:09

GMB