-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_stack_v+e.py
36 lines (30 loc) · 1.02 KB
/
AC_stack_v+e.py
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
27
28
29
30
31
32
33
34
35
36
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_stack_v+e.py
# Create Date: 2015-08-10 22:23:30
# Usage: AC_queue_v+e.py
# Descripton:
import collections
class Solution:
# @param {integer} numCourses
# @param {integer[][]} prerequisites
# @return {boolean}
def canFinish(self, numCourses, prerequisites):
# in order and reverse order
graph = collections.defaultdict(set)
rev = collections.defaultdict(set)
for cur, pre in prerequisites:
graph[cur].add(pre)
rev[pre].add(cur)
# get the 0 in-order nodes into the stack
stack = [n for n in range(numCourses) if not graph[n]]
cnt = 0
while stack:
node = stack.pop()
cnt += 1
for pre in rev[node]:
graph[pre].remove(node)
if not graph[pre]:
stack.append(pre)
return cnt == numCourses