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 30 31 32 33 34 35
| class Solution { public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { Map<Integer, List<Integer>> nodeToNodeListMap = new HashMap<>(); for (int[] prerequisite : prerequisites) { int from = prerequisite[0], to = prerequisite[1]; nodeToNodeListMap.computeIfAbsent(from, key -> new ArrayList<>()).add(to); }
List<Boolean> resultList = new ArrayList<>(queries.length); Boolean[][] dfsCache = new Boolean[numCourses][numCourses]; for (int[] query : queries) { resultList.add(dfs(dfsCache,nodeToNodeListMap, query[0], query[1])); } return resultList; }
private Boolean dfs(Boolean[][] dfsCache, Map<Integer, List<Integer>> nodeToNodeListMap, int from, int to) { if (dfsCache[from][to] != null) { return dfsCache[from][to]; } if (from == to) { return true; }
for (int node : nodeToNodeListMap.getOrDefault(from, Collections.emptyList())) { if (dfs(dfsCache, nodeToNodeListMap, node, to)) { return true; } }
dfsCache[from][to] = false; return false; } }
|