Find ancestors of each node in the given Graph
Given a graph in the form of an edge list and a directed graph, return all the ancestors of the nodes in any order. An ancestor is a node one step ahead in the hierarchy on the same path reachable to the current node.
Note: The graph has no cycle.
Examples:
Input: N = 5, Edges[][2] = {{0, 4}, {4, 1}, {4, 3}, {1, 2}}
Output: Result[N][] = {{}, {0, 4}, {0, 1, 4}, {0, 4}, {0}}
Explanation:As the graph shows the that there are no ancestors to node 0 hence the value of Result[0][] = {} and for the rest of the nodes all the ancestors are given in their respective indices sorted in ascending order.
Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 4}, {2, 5}, {4, 3}, {4, 5}, {6, 3}, {6, 5}}
Output: Result[N][] = {{}, {0}, {0}, {0, 1, 2, 4, 6}, {0, 1, 2}, {0, 1, 2, 4, 6}, {}}
Approach: To solve the problem follow the below idea:
The idea is to store the edges in the adjacency list such that the direction of the edges is reversed. Then perform DFS from all nodes until we exhaust the DFS, and all the nodes visited for a particular node will be its ancestors as all the edges are reversed.
- Reverse the edges and store them in the adjacency list adj.
- For each node from 0 to n – 1, call DFS and store all the nodes into the vector reached by the DFS.
- Store this resultant vector into a 2D vector.
Below is the implementation of the above approach:
C++
|
0 -> 1 -> 0 4 2 -> 0 1 4 3 -> 0 4 4 -> 0
Time Complexity: O(V2)
Auxiliary Space: O(|V| + |E|)
Given a graph in the form of an edge list and a directed graph, return all the ancestors of the nodes in any order. An ancestor is a node one step ahead in the hierarchy on the same path reachable to the current node.
Note: The graph has no cycle.
Examples:
Input: N = 5, Edges[][2] = {{0, 4}, {4, 1}, {4, 3}, {1, 2}}
Output: Result[N][] = {{}, {0, 4}, {0, 1, 4}, {0, 4}, {0}}
Explanation:As the graph shows the that there are no ancestors to node 0 hence the value of Result[0][] = {} and for the rest of the nodes all the ancestors are given in their respective indices sorted in ascending order.
Input: N = 7, Edges[][2] = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 4}, {2, 5}, {4, 3}, {4, 5}, {6, 3}, {6, 5}}
Output: Result[N][] = {{}, {0}, {0}, {0, 1, 2, 4, 6}, {0, 1, 2}, {0, 1, 2, 4, 6}, {}}
Approach: To solve the problem follow the below idea:
The idea is to store the edges in the adjacency list such that the direction of the edges is reversed. Then perform DFS from all nodes until we exhaust the DFS, and all the nodes visited for a particular node will be its ancestors as all the edges are reversed.
- Reverse the edges and store them in the adjacency list adj.
- For each node from 0 to n – 1, call DFS and store all the nodes into the vector reached by the DFS.
- Store this resultant vector into a 2D vector.
Below is the implementation of the above approach:
C++
|
0 -> 1 -> 0 4 2 -> 0 1 4 3 -> 0 4 4 -> 0
Time Complexity: O(V2)
Auxiliary Space: O(|V| + |E|)