Skip to content

Instantly share code, notes, and snippets.

@liondancer
Created January 9, 2017 17:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liondancer/997b1bc61af8678ce7948617c245f284 to your computer and use it in GitHub Desktop.
Save liondancer/997b1bc61af8678ce7948617c245f284 to your computer and use it in GitHub Desktop.
def findOrder(numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
if prerequisites:
d = {}
for i in range(numCourses):
d[i] = set()
for c in prerequisites:
d[c[0]].add(c[1])
q = []
for i in d:
if not d[i]:
q.append(i)
res = []
while q:
n = q.pop()
res.append(n)
for c,r in d.items():
if n in r:
d[c].remove(n)
if not d[c]:
q.append(c)
if len(res) != numCourses:
return []
return res
else:
return [i for i in range(numCourses)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment