Course Schedule II
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 return the ordering of courses you should take to finish all courses.
If there are multiple valid orderings, return any valid ordering. If it is impossible to finish all courses, return an empty array.
EXAMPLES
Example 1:
Input:
numCourses = 4 prerequisites = [[1,0], [2,0], [3,1], [3,2]]
Output: [0, 1, 2, 3] or [0, 2, 1, 3]
Explanation: There are a couple of ways to complete all courses, one possible order is [0, 1, 2, 3] and another is [0, 2, 1, 3].
Example 2:
Input:
numCourses = 2 prerequisites = [[1, 0], [0, 1]]
Output: []
Explanation: It is impossible to finish all courses, as you must finish course 0 before course 1 and course 1 before course 0.
Run your code to see results here
Explanation
Solution
from collections import defaultdict, dequeclass Solution:def findOrder(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])order = []while queue:course = queue.popleft()order.append(course)for neighbor in graph[course]:in_degree[neighbor] -= 1if in_degree[neighbor] == 0:queue.append(neighbor)return order if len(order) == numCourses else []
Loading comments...