Given an undirected non-weighted graph G. For a given node start return the shortest path that is the number of edges from start to all the nodes in the complement graph of G.
Complement Graph is a graph such that it contains only those edges which are not present in the original graph.
Input: Undirected Edges = (1, 2), (1, 3), (3, 4), (3, 5), Start = 1
Output: 0 2 3 1 1
The distance from 1 to every node in the complement graph are:
1 to 1 = 0,
1 to 2 = 2,
1 to 3 = 3,
1 to 4 = 1,
1 to 5 = 1
Naive Approach: A Simple solution will be to create the complement graph and use Breadth-First Search on this graph to find the distance to all the nodes.
Time complexity: O(n2) for creating the complement graph and O(n + m) for breadth first search.
Efficient Approach: The idea is to use Modified Breadth-First Search to calculate the answer and then there is no need to construct the complement graph.
- For each vertex or node, reduce the distance of a vertex which is a complement to the current vertex and has not been discovered yet.
- For the problem, we have to observe that if the Graph is Sparse then the undiscovered nodes will be visited very fast.
Below is the implementation of the above approach:
0 2 3 1 1
Time complexity: O(V+E)
Auxiliary Space: O(V)