LmaoSuVuong
Senior Member
Java:
class Solution {
public List<List<Integer>> getAncestors(int n, int[][] edges) {
List<Integer>[] adjacents = new ArrayList[n];
List<Integer>[] ancestors = new ArrayList[n];
List<List<Integer>> res = new ArrayList<>();
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
adjacents[i] = new ArrayList<>();
ancestors[i] = new ArrayList<>();
}
for (int[] edge : edges) {
adjacents[edge[1]].add(edge[0]);
}
for(int i= 0 ; i < n ;i++){
dfs(i, adjacents,visited,ancestors);
Collections.sort(ancestors[i]);
res.add(ancestors[i]);
}
return res;
}
public List<Integer> dfs(int node, List<Integer>[] adjacents, boolean[] visited, List<Integer>[] ancestors) {
if (visited[node] == true) {
return ancestors[node];
}
Set<Integer> ancestor = new HashSet();
for (int adjacent : adjacents[node]) {
ancestor.add(adjacent);
ancestor.addAll(dfs(adjacent, adjacents, visited,ancestors));
}
visited[node] = true;
ancestors[node] = new ArrayList<>(ancestor);
return ancestors[node];
}
}
Last edited: