Learn DSA
Two Pointers
Sliding Window
Intervals
Stack
Linked List
Binary Search
Heap
Depth-First Search
Breadth-First Search
Backtracking
Graphs
Dynamic Programming
Greedy Algorithms
Trie
Prefix Sum
Matrices
Course Schedule
DESCRIPTION (credit Leetcode.com)
You have to take a total of numCourses courses, which are labeled from 0 to numCourses - 1. You are given a list of prerequisites pairs, where prerequisites[i] = [a, b] indicates that you must complete course b before course a.
Given the total number of courses and a list of prerequisite pairs, write a function to determine if it is possible to finish all courses.
EXAMPLES
Example 1:
Input:
numCourses = 3 prerequisites = [[1, 0], [2, 1]]
Output: true
Explanation: You can take courses in the following order: 0, 1, 2.
Example 2:
Input:
numCourses = 3 prerequisites = [[1, 0], [0, 1],[1,2]]
Output: false
Explanation: It is impossible to finish all courses, as you must finish course 1 before course 0 and course 0 before course 1.
Run your code to see results here
Explanation
- Start with a course that has no prerequisites.
- If that course is a prerequisite for another course, remove it from the prerequisites list.
- Now, Find the next course that has no prerequisites, and repeat the process.
- If we have already taken all the courses, then we can return true.
- Otherwise, we return false (as this means there was a circular dependency in the prerequisites).
Cycle
Topological Sort
from collections import defaultdict, dequeclass Solution:def canFinish(self, numCourses, prerequisites):graph = defaultdict(list)in_degree = [0] * numCoursesfor dest, src in prerequisites:graph[src].append(dest)in_degree[dest] += 1queue = deque([i for i in range(numCourses) if in_degree[i] == 0])courses_taken = 0while queue:course = queue.popleft()courses_taken += 1for neighbor in graph[course]:in_degree[neighbor] -= 1if in_degree[neighbor] == 0:queue.append(neighbor)return courses_taken == numCourses
Loading comments...