public boolean canFinish(int numCourses, int[][] prerequisites) { ArrayList[] graph = new ArrayList[numCourses]; int[] in = new int[numCourses]; for (int i = 0; i < numCourses; ++i) { graph[i] = new ArrayList<>(); } for (int[] p : prerequisites) { graph[p[1]].add(p[0]); in[p[0]]++; } Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < numCourses; ++i) { if (in[i] == 0) q.offer(i); } while (!q.isEmpty()) { int pre = q.poll(); for (int i = 0; i < graph[pre].size(); ++i) { int post = (int) graph[pre].get(i); --in[post]; if (in[post] == 0) q.offer(post); } } for (int i = 0; i < numCourses; ++i) { if (in[i] != 0) return false; } return true; }
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { vector<vector<int>> graph(numCourses, vector<int>()); vector<int> in(numCourses); for (auto a : prerequisites) { graph[a[1]].push_back(a[0]); ++in[a[0]]; } queue<int> q; for (int i = 0; i < numCourses; ++i) { if (in[i] == 0) q.push(i); } while (!q.empty()) { int t = q.front(); q.pop(); for (int i : graph[t]) { --in[i]; if (in[i] == 0) q.push(i); } } for (int i = 0; i < numCourses; ++i) { if (in[i] != 0) return false; } return true; }