You are given an undirected graph with 'N' nodes and 'M' edges. The weight of each edge in the graph is one unit.
Given a source vertex 'src', you must return an array 'answer' of length 'N', where 'answer[i]' is the shortest path length between the source vertex 'src' and 'i'th vertex.
All the nodes are zero-based.
Example:
Input:
N=5, M=5, edges=[(0, 1), (1, 4), (2, 3), (2, 4), (3, 4)], src=1
Output: 1 0 2 2 1

Explanation: The path from vertices are:-
(1->0) = 1 -> 0, path length is 1.
(1->1) = 1 -> 1, path length is 0.
(1->2) = 1 -> 4 -> 2, the path length is 2.
(1->3) = 1 -> 4 -> 3, path length is 2.
(1->4) = 1 -> 4, the path length is 1.
Hence we return [1, 0, 2, 2, 1]
The first line of the input will contain integers 'N' and 'M', denoting the number of nodes and the number of edges.
The next 'M' lines contain two space-separated integers, denoting an undirected edge between 'a' and 'b'.
The next line contains an integer denoting 'src'.
Output Format:-
The only line contains 'N' space-separated integers, i.e., the path length to each node.
Note:-
You don't need to print anything. Just implement the given function.
4 3
0 1
0 3
2 3
0
0 1 2 1
For test case one:
Input:
N=4, M=3, edges=[(0, 1), (0, 3), (2, 3)], src=0
Output: 0 1 2 1
Explanation: The path from vertices are:-
(0->0) = 0 -> 0, path length is 0.
(0->1) = 0 -> 1, path length is 1.
(0->2) = 0 -> 3 -> 2, path length is 2.
(0->3) = 0 -> 2, path length is 1.
Hence we return [0, 1, 2, 1]
3 3
0 1
1 2
0 2
2
1 1 0
1 <= N, M <= 10^2
0 <= src, edges[0], edges[0] <= N-1
Time Limit: 1 sec
Perform DFS for each of the nodes.
Approach:
Algorithm:
Function void DFS(int node, int dest, int[][] adjacencyList, int &minimumLength, int currentLength):
Function int[] shortestPath(int n, int[] edges, int src):
O( N*(N+M) ), Where ‘N’ is the number of nodes and ‘M’ is the total edges in the graph.
For each vertex in the graph, we are doing a DFS, which takes O(N+M) time in the worst case. Hence the total time complexity is O(N*(N+M)).
O( N ), Where ‘N’ is the number of nodes in the graph.
We are taking O( N ) extra space. Hence, the overall space complexity will be O( N ).