deno.land / x / masx200_leetcode_test@10.6.5 / all-ancestors-of-a-node-in-a-directed-acyclic-graph / index.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export default function getAncestors(n: number, edges: number[][]): number[][] { const childToParents: Map<number, Set<number>> = new Map();
for (const [parent, child] of edges) { let set = childToParents.get(child); if (!set) { set = new Set(); childToParents.set(child, set); } set.add(parent); } return Array.from({ length: n }).map((_, i) => handle_graph(childToParents, i) );}
function handle_graph(childToParents: Map<number, Set<number>>, i: number) { const Ancestors = new Set<number>(); function callbackfn(v: number) { if (!Ancestors.has(v)) { Ancestors.add(v);
childToParents.get(v)?.forEach(callbackfn); } } childToParents.get(i)?.forEach(callbackfn); return Array.from(Ancestors).sort((a, b) => a - b);}
masx200_leetcode_test

Version Info

Tagged at
a year ago