MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / canFinish

Method canFinish

207-course-schedule/course-schedule.java:6–41  ·  view source on GitHub ↗
(int numCourses, int[][] prerequisites)

Source from the content-addressed store, hash-verified

4
5class Solution {
6 public boolean canFinish(int numCourses, int[][] prerequisites) {
7 // Build graph
8 List<Integer>[] graph = new ArrayList[numCourses];
9 for (int i = 0; i < numCourses; i++) {
10 graph[i] = new ArrayList<>();
11 }
12 int[] indegree = new int[numCourses];
13
14 for (int[] pre : prerequisites) {
15 graph[pre[1]].add(pre[0]);
16 indegree[pre[0]]++;
17 }
18
19 // BFS - Kahn's algorithm
20 Queue<Integer> queue = new LinkedList<>();
21 for (int i = 0; i < numCourses; i++) {
22 if (indegree[i] == 0) {
23 queue.add(i);
24 }
25 }
26
27 int count = 0;
28 while (!queue.isEmpty()) {
29 int course = queue.poll();
30 count++;
31
32 for (int neighbor : graph[course]) {
33 indegree[neighbor]--;
34 if (indegree[neighbor] == 0) {
35 queue.add(neighbor);
36 }
37 }
38 }
39
40 return count == numCourses;
41 }
42}

Callers

nothing calls this directly

Calls 1

isEmptyMethod · 0.80

Tested by

no test coverage detected