Given a directed graph and a node X. The task is to find the minimum number of edges that must be added to the graph such that any node can be reachable from the given node.
Input: X = 0
Input: X = 4
Approach: First, let’s mark all the vertices reachable from X as good, using a simple DFS. Then, for each bad vertex (vertices which are not reachable from X) v, count the number of bad vertices reachable from v (it also can be done by simple DFS). Let this number be cntv. Now, iterate over all bad vertices in non-increasing order of cntv. For the current bad vertex v, if it is still not marked as good, run a DFS from it, marking all the reachable vertices as good, and increase the answer by 1 (in fact, we are implicitly adding the edge (s, v)). It can be proved that this solution gives an optimal answer.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price.