![]() |
VOOZH | about |
Suppose there are n towns connected by m bidirectional roads. There are s towns among them with a police station. We want to find out the distance of each town from the nearest police station. If the town itself has one the distance is 0.
Example:
Input : Number of Vertices = 6 Number of Edges = 9 Towns with Police Station : 1, 5 Edges: 1 2 1 6 2 6 2 3 3 6 5 4 6 5 3 4 5 3
Output : 1 0 2 1 3 1 4 1 5 0 6 1
Naive Approach: We can loop through the vertices and from each vertex run a BFS to find the closest town with police station from that vertex. This will take O(V.E).
Naive approach implementation using BFS from each vertex:
1 0 2 1 3 1 4 1 5 0 6 1
Complexity Analysis:
Efficient Method A better method is to use the Dijkstra's algorithm in a modified way. Let's consider one of the sources as the original source and the other sources to be vertices with 0 cost paths from the original source. Thus we push all the sources into the Dijkstra Queue with distance = 0, and the rest of the vertices with distance = infinity. The minimum distance of each vertex from the original source now calculated using the Dijkstra's Algorithm are now essentially the distances from the nearest source.
Explanation:
The C++ implementation uses a set of pairs (distance from the source, vertex) sorted according to the distance from the source. Initially, the set contains the sources with distance = 0 and all the other vertices with distance = infinity.
On each step, we will go to the vertex with minimum distance(d) from source, i.e, the first element of the set (the source itself in the first step with distance = 0). We go through all it's adjacent vertices and if the distance of any vertex is > d + 1 we replace its entry in the set with the new distance. Then we remove the current vertex from the set. We continue this until the set is empty.
The idea is there cannot be a shorter path to the vertex at the front of the set than the current one since any other path will be a sum of a longer path (>= it's length) and a non-negative path length (unless we are considering negative edges).
Since all the sources have a distance = 0, in the beginning, the adjacent non-source vertices will get a distance = 1. All vertices will get distance = distance from their nearest source.
Implementation of Efficient Approach:
1 0 2 1 3 1 4 1 5 0 6 1
Complexity Analysis:
More Efficient Approach: An even better method is to use the Multisource BFS which is a modification of BFS.We will put the all source vertices to the queue at first rather than a single vertex which was in case of standard BFS.This way Multisource BFS will first visit all the source vertices. After that it will visit the vertices which are at a distance of 1 from all source vertices, then at a distance of 2 from all source vertices and so on and so forth.
Below is the implementation of the above approach:
1 0 2 1 3 1 4 1 5 0 6 1
Complexity Analysis: