Course Schedule IV LeetCode solution in Java

1
class Solution {
2
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
3
// Generating Map
4
Map<Integer, List<Integer>> graph = new HashMap<>();
5
for (int e[] : prerequisites) {
6
graph.putIfAbsent(e[0], new ArrayList<>());
7
graph.get(e[0]).add(e[1]);
8
}
9

10
List<Boolean> list = new ArrayList<>();
11
// Appling DFS for every query to get result
12
for (int[] q : queries) {
13
list.add(isPre(q[0], q[1], graph, new HashSet<>()));
14
}
15
return list;
16
}
17

18
// Check if src comes before dst using DFS
19
private boolean isPre(int src, int dst, Map<Integer, List<Integer>> adj, Set<Integer> visited) {
20
if (visited.contains(src)) return false;
21
visited.add(src);
22
for (int neigh : adj.getOrDefault(src, new ArrayList<>())) {
23
if (neigh == dst || isPre(neigh, dst, adj, visited)) return true;
24
}
25
return false;
26
}
27
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0