2192. All Ancestors of a Node in a Directed Acyclic Graph Medium

@problem@discussion
#Depth-First Search#Breadth-First Search#Graph#Topological Sort



1/**
2 * [2192] All Ancestors of a Node in a Directed Acyclic Graph
3 *
4 * You are given a positive integer n representing the number of nodes of a Directed Acyclic Graph (DAG). The nodes are numbered from 0 to n - 1 (inclusive).
5 * You are also given a 2D integer array edges, where edges[i] = [fromi, toi] denotes that there is a unidirectional edge from fromi to toi in the graph.
6 * Return a list answer, where answer[i] is the list of ancestors of the i^th node, sorted in ascending order.
7 * A node u is an ancestor of another node v if u can reach v via a set of edges.
8 *  
9 * Example 1:
10 * <img alt="" src="https://assets.leetcode.com/uploads/2019/12/12/e1.png" style="width: 322px; height: 265px;" />
11 * Input: n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
12 * Output: [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
13 * Explanation:
14 * The above diagram represents the input graph.
15 * - Nodes 0, 1, and 2 do not have any ancestors.
16 * - Node 3 has two ancestors 0 and 1.
17 * - Node 4 has two ancestors 0 and 2.
18 * - Node 5 has three ancestors 0, 1, and 3.
19 * - Node 6 has five ancestors 0, 1, 2, 3, and 4.
20 * - Node 7 has four ancestors 0, 1, 2, and 3.
21 * 
22 * Example 2:
23 * <img alt="" src="https://assets.leetcode.com/uploads/2019/12/12/e2.png" style="width: 343px; height: 299px;" />
24 * Input: n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
25 * Output: [[],[0],[0,1],[0,1,2],[0,1,2,3]]
26 * Explanation:
27 * The above diagram represents the input graph.
28 * - Node 0 does not have any ancestor.
29 * - Node 1 has one ancestor 0.
30 * - Node 2 has two ancestors 0 and 1.
31 * - Node 3 has three ancestors 0, 1, and 2.
32 * - Node 4 has four ancestors 0, 1, 2, and 3.
33 * 
34 *  
35 * Constraints:
36 * 
37 * 	1 <= n <= 1000
38 * 	0 <= edges.length <= min(2000, n * (n - 1) / 2)
39 * 	edges[i].length == 2
40 * 	0 <= fromi, toi <= n - 1
41 * 	fromi != toi
42 * 	There are no duplicate edges.
43 * 	The graph is directed and acyclic.
44 * 
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/
49// discuss: https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54    pub fn get_ancestors(n: i32, edges: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
55        vec![]
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_2192() {
67    }
68}
69


Back
© 2025 bowen.ge All Rights Reserved.