-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 228 ms (17.81%), Space: 64.3 MB (90.34%) - LeetHub
- Loading branch information
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
...in-a-directed-acyclic-graph/2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import java.util.*; | ||
class Solution { | ||
public static ArrayList<Integer> bfs(ArrayList<ArrayList<Integer>> adjList, int start) { | ||
Queue<Integer> queue = new ArrayDeque<>(); | ||
ArrayList<Integer> ans = new ArrayList<>(); | ||
// 메모리 초과 나면, ArrayList에 넣어서 sort 하는걸로 시도 | ||
TreeSet<Integer> set = new TreeSet<>(); | ||
queue.offer(start); | ||
set.add(start); | ||
while (!queue.isEmpty()) { | ||
int target = queue.poll(); | ||
for (int elem : adjList.get(target)) { | ||
if (!set.contains(elem)) { | ||
set.add(elem); | ||
queue.offer(elem); | ||
} | ||
} | ||
} | ||
for (int elem : set) { | ||
if (elem != start) { | ||
ans.add(elem); | ||
} | ||
} | ||
return ans; | ||
} | ||
public List<List<Integer>> getAncestors(int n, int[][] edges) { | ||
ArrayList<ArrayList<Integer>> adjList = new ArrayList<>(); | ||
List<List<Integer>> answer = new ArrayList<>(); | ||
for (int i = 0; i < n; i++) { | ||
adjList.add(new ArrayList<>()); | ||
} | ||
for (int[] edge : edges) { | ||
int start = edge[0]; | ||
int end = edge[1]; | ||
adjList.get(end).add(start); | ||
} | ||
for (int i = 0; i < n; i++) { | ||
answer.add(bfs(adjList, i)); | ||
} | ||
return answer; | ||
} | ||
} |