Sum of minimum element at each depth of a given non cyclic graph
Given a non-cyclic graph having V nodes and E edges and a source node S, the task is to calculate the sum of the minimum element at each level from source node S in the given graph.
Input: S = 0, Below is the given graph
There is only one node at depth 0 i.e. 0.
At depth 1 there are 3 nodes 1, 2, 3, and minimum of them is 1.
At depth 2 there are another 3 nodes i.e. 6, 4, 5, and a minimum of them is 4.
So the sum of minimum element at each depth is 0 + 1 + 4 = 5.
Input: S = 2, Below is the given graph
At depth 0 only 1 node exists i.e. 2.
At depth 1 minimum element is 0.
At depth 2 minimum element is 1.
At depth 3 minimum element is 5
So the sum of minimum element at each depth is 2 + 0 + 1 + 5 = 8.
Approach: The idea is to use DFS Traversal. Below are the steps:
- Initialize an array(say arr) to store the minimum element at each level.
- Start the DFS Traversal from the given source node S with a variable depth(initially 0).
- Update the minimum value of current depth in the array arr.
- Recursively recurr for child node with incrementing the value of depth from the previous recursive call such that the minimum value at corresponding depth can be updated accordingly.
- After the above steps the sum of values stored in arr is the required total sum.
Below is the implementation of the above approach:
Time Complexity: O(V + E)
Auxiliary Space: O(V)