Skip to content

Commit bcd0697

Browse files
authored
Create 2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.js
1 parent eddbba5 commit bcd0697

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number[][]}
5+
*/
6+
const getAncestors = function(n, edges) {
7+
const res = Array.from({ length: n }, () => new Set())
8+
const inDegree = Array(n).fill(0)
9+
const graph = {}
10+
11+
for(const [u, v] of edges) {
12+
if(graph[v] == null) graph[v] = []
13+
graph[v].push(u)
14+
inDegree[v]++
15+
}
16+
17+
const visited = Array(n).fill(false)
18+
for (let i = 0; i < n; i++) {
19+
if (!visited[i]) dfs(i);
20+
}
21+
22+
return res.map(set => Array.from(set).sort((a, b) => a - b))
23+
24+
function dfs(i) {
25+
visited[i] = true
26+
for(const p of (graph[i] || [])) {
27+
if(visited[p] === false) dfs(p)
28+
res[i].add(p)
29+
for(const e of res[p]) res[i].add(e)
30+
}
31+
}
32+
};

0 commit comments

Comments
 (0)