Skip to content

Commit a86b815

Browse files
committed
Solve 210 with Python
1 parent 0131137 commit a86b815

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
# Author: illuz <iilluzen[at]gmail.com>
4+
# File: AC_stack_v+e.py
5+
# Create Date: 2016-02-25 19:31:07
6+
# Usage: AC_stack_v+e.py
7+
# Descripton: just as the 207
8+
9+
class Solution:
10+
# @param {integer} numCourses
11+
# @param {integer[][]} prerequisites
12+
# @return {boolean}
13+
def findOrder(self, numCourses, prerequisites):
14+
# in order and reverse order
15+
graph = collections.defaultdict(set)
16+
rev = collections.defaultdict(set)
17+
18+
for cur, pre in prerequisites:
19+
graph[cur].add(pre)
20+
rev[pre].add(cur)
21+
22+
# get the 0 in-order nodes into the stack
23+
stack = [n for n in range(numCourses) if not graph[n]]
24+
path = []
25+
cnt = 0
26+
while stack:
27+
node = stack.pop()
28+
path.append(node)
29+
cnt += 1
30+
for pre in rev[node]:
31+
graph[pre].remove(node)
32+
if not graph[pre]:
33+
stack.append(pre)
34+
return path if cnt == numCourses else []
35+

0 commit comments

Comments
 (0)