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)
- Multistage Graph (Shortest Path)
- Shortest path in an unweighted graph
- 0-1 BFS (Shortest Path in a Binary Weight Graph)
- Shortest Path in Directed Acyclic Graph
- Shortest path with exactly k edges in a directed and weighted graph
- Shortest Path in a weighted Graph where weight of an edge is 1 or 2
- Shortest path with exactly k edges in a directed and weighted graph | Set 2
- Shortest path in a directed graph by Dijkstra’s algorithm
- Multi Source Shortest Path in Unweighted Graph
- Check if given path between two nodes of a graph represents a shortest paths
- Building an undirected graph and finding shortest path using Dictionaries in Python
- Shortest path in a graph from a source S to destination D with exactly K edges for multiple Queries
- Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Shortest path on a Square
- Shortest Path Faster Algorithm
- Some interesting shortest path questions | Set 1
- Shortest path in a Binary Maze
- Shortest Path using Meet In The Middle
- Dijkstra’s shortest path algorithm using set in STL
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.