Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit eea5ab9

Browse files
Merge pull request #56 from codewithhridoy/javascript
medium: 2192. All Ancestors of a Node in a Directed Acyclic Graph
2 parents 0aaa92d + 92fec57 commit eea5ab9

File tree

2 files changed

+127
-0
lines changed

2 files changed

+127
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number[][]}
5+
*/
6+
function getAncestors(n, edges) {
7+
// Create an adjacency list to represent the graph
8+
const adjList = Array.from({ length: n }, () => []);
9+
const inDegree = Array(n).fill(0);
10+
11+
for (const [from, to] of edges) {
12+
adjList[from].push(to);
13+
inDegree[to]++;
14+
}
15+
16+
// Initialize a list to store ancestors for each node
17+
const ancestors = Array.from({ length: n }, () => new Set());
18+
19+
// Topological sort using Kahn's algorithm
20+
const queue = [];
21+
for (let i = 0; i < n; i++) {
22+
if (inDegree[i] === 0) {
23+
queue.push(i);
24+
}
25+
}
26+
27+
while (queue.length > 0) {
28+
const node = queue.shift();
29+
for (const neighbor of adjList[node]) {
30+
ancestors[neighbor].add(node);
31+
for (const anc of ancestors[node]) {
32+
ancestors[neighbor].add(anc);
33+
}
34+
inDegree[neighbor]--;
35+
if (inDegree[neighbor] === 0) {
36+
queue.push(neighbor);
37+
}
38+
}
39+
}
40+
41+
// Convert sets to sorted arrays
42+
return ancestors.map(ancestorSet => Array.from(ancestorSet).sort((a, b) => a - b));
43+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# [2192. All Ancestors of a Node in a Directed Acyclic Graph](https://leetcode.com/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph)
2+
3+
---
4+
5+
title: "Finding Ancestors in a Directed Acyclic Graph"
6+
summary: "A solution to find all ancestors of each node in a directed acyclic graph using topological sorting."
7+
date: "2024年06月29日"
8+
modifiedDate: "2024年06月29日"
9+
tags: ["graph theory", "topological sort", "algorithms"]
10+
slug: "finding-ancestors-in-dag"
11+
12+
---
13+
14+
# Intuition
15+
16+
The problem requires us to find all ancestors for each node in a directed acyclic graph (DAG). An ancestor of a node `u` is any node `v` such that there is a path from `v` to `u`. To solve this problem, we need to track all such paths and determine which nodes lead to each other.
17+
18+
# Approach
19+
20+
1. **Graph Representation**: Represent the graph using an adjacency list.
21+
2. **Topological Sorting**: Use Kahn's algorithm to perform topological sorting. This helps in processing nodes in a linear order such that every directed edge `u -> v`, `u` comes before `v`.
22+
3. **Tracking Ancestors**: For each node processed, update the ancestors of its neighbors by adding the current node and all its ancestors.
23+
24+
## Steps:
25+
26+
- Create an adjacency list and an in-degree array.
27+
- Perform topological sorting using Kahn's algorithm.
28+
- As each node is processed, update the ancestors of its neighbors.
29+
30+
# Complexity
31+
32+
- Time complexity: $$O(n + e)$$ where `n` is the number of nodes and `e` is the number of edges, due to the graph traversal and ancestor updates.
33+
34+
- Space complexity: $$O(n^2)$$ in the worst case for storing the ancestors for each node.
35+
36+
# Code
37+
38+
```javascript
39+
/**
40+
* @param {number} n
41+
* @param {number[][]} edges
42+
* @return {number[][]}
43+
*/
44+
function getAncestors(n, edges) {
45+
// Create an adjacency list to represent the graph
46+
const adjList = Array.from({ length: n }, () => []);
47+
const inDegree = Array(n).fill(0);
48+
49+
for (const [from, to] of edges) {
50+
adjList[from].push(to);
51+
inDegree[to]++;
52+
}
53+
54+
// Initialize a list to store ancestors for each node
55+
const ancestors = Array.from({ length: n }, () => new Set());
56+
57+
// Topological sort using Kahn's algorithm
58+
const queue = [];
59+
for (let i = 0; i < n; i++) {
60+
if (inDegree[i] === 0) {
61+
queue.push(i);
62+
}
63+
}
64+
65+
while (queue.length > 0) {
66+
const node = queue.shift();
67+
for (const neighbor of adjList[node]) {
68+
ancestors[neighbor].add(node);
69+
for (const anc of ancestors[node]) {
70+
ancestors[neighbor].add(anc);
71+
}
72+
inDegree[neighbor]--;
73+
if (inDegree[neighbor] === 0) {
74+
queue.push(neighbor);
75+
}
76+
}
77+
}
78+
79+
// Convert sets to sorted arrays
80+
return ancestors.map((ancestorSet) =>
81+
Array.from(ancestorSet).sort((a, b) => a - b)
82+
);
83+
}
84+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /