As the title said, I'm trying to implement an algorithm that finds out the distances between all pairs of nodes in given graph. But there is more: (Things that might help you)
|E| <= 4*|V|
I know about Johnson's algorithm, Floyd-Warshal, and Dijkstra for all pairs. But these algorithms are good when the graph has weights.
I was wondering if there is a better algorithm for my case, because those algorithms are intended for weighted graphs.
Thanks!
Dijkstra's Algorithm. This algorithm might be the most famous one for finding the shortest path. Its advantage over a DFS, BFS, and bidirectional search is that you can use it in all graphs with positive edge weights.
The idea is to use BFS . One important observation about BFS is, the path used in BFS always has least number of edges between any two vertices. So if all edges are of same weight, we can use BFS to find the shortest path.
Dijkstra's Algorithm finds the shortest path between a given node (which is called the "source node") and all other nodes in a graph. This algorithm uses the weights of the edges to find the path that minimizes the total distance (weight) between the source node and all other nodes.
The Floyd Warshall Algorithm is for solving all pairs shortest path problems. The problem is to find the shortest distances between every pair of vertices in a given edge-weighted directed Graph.
There is space for improvement because in unweighted graphs, you gain an additional attribute which does not hold for weighted graphs, namely:
For any edge directly connecting A to C, you know for sure that there is no shorter path via a third node B.
With this in mind, you should be able to simplify Dijkstra's Algorithm: As you may know, it works with three sets of nodes:
When following an edge e
from A
(1.) to C
(3.), original Dijkstra would move node C
from (3.) to (2.). Since the above attribute holds in all your graphs, you can however add it directly to the set (1.), which is more efficient.
Here's the essential observation: The procedure outlined above is basically a BFS (breadth first search), i.e. you can find the distance from some fixed node v
to any other node in O(|V| + |E|)
.
You did not mention in your original question that the graph was basically a grid with some holes in it. This is an even stronger requirement, and I am sure you can exploit it. Doing a quick search for "grid graph shortest path" yields this paper which promises O(sqrt(n))
in the best case. As the problem you specify is fairly well-structured, I'm almost sure there are several more papers which you might want to look into.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With