-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.py
More file actions
26 lines (22 loc) · 827 Bytes
/
Copy pathsolution.py
File metadata and controls
26 lines (22 loc) · 827 Bytes
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
from collections import deque
class Solution:
def findOrder(self, n, prerequisites):
# adjacency list and indegree
adj = [[] for _ in range(n)]
indeg = [0] * n
for x, y in prerequisites:
# to take x, must finish y first -> y -> x
adj[y].append(x)
indeg[x] += 1
# start with all courses having indegree 0
q = deque([i for i in range(n) if indeg[i] == 0])
order = []
while q:
node = q.popleft()
order.append(node)
for nei in adj[node]:
indeg[nei] -= 1
if indeg[nei] == 0:
q.append(nei)
# if we scheduled all courses, return order; else a cycle exists
return order if len(order) == n else []