Byleth_CYY

Course schedule II

Apr 8th, 2020
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1.  
  2. class Graph:
  3.     def __init__(self,x,mylist):
  4.         self.label=x
  5.         self.neighbors=mylist
  6.  
  7. class Solution:
  8.     """
  9.    @param: numCourses: a total of n courses
  10.    @param: prerequisites: a list of prerequisite pairs
  11.    @return: the course order
  12.    """
  13.     def findOrder(self, numCourses, prerequisites):
  14.         # write your code here
  15.         if len(prerequisites)==0:
  16.             return [i for i in range(numCourses)]
  17.        
  18.        
  19.         all_course=[[i] for i in range(numCourses)]
  20.         for i in range(len(prerequisites)):
  21.             all_course[prerequisites[i][0]].append(prerequisites[i][1])
  22.        
  23.         start_point=False
  24.         graphs=[]
  25.         for i in range(len(all_course)):
  26.             #temp_graph=Graph(i)
  27.             if len(all_course[i])>1:
  28.                 graphs.append(Graph(i,all_course[i][1:]))
  29.             else:
  30.                 start_point=True
  31.                 graphs.append(Graph(i,[]))
  32.            
  33.         #print(graphs[0].label)
  34.        
  35.         if not start_point:
  36.             return []
  37.        
  38.         course_taken={}
  39.         course_order=[]
  40.         def topsort(mygraph):
  41.             if mygraph.label in course_taken:
  42.                 return
  43.            
  44.             if len(mygraph.neighbors)>0:
  45.                 for i in range(len(mygraph.neighbors)):
  46.                     topsort(mygraph.neighbors[i])
  47.             course_taken[mygraph.label]=1
  48.             course_order.append(mygraph.label)
  49.        
  50.         for i in range(len(graphs)):
  51.             #print(graphs[i][0])
  52.             topsort(graphs[i])
  53.             if len(course_taken)==numCourses:
  54.                 break
  55.        
  56.         return course_order[::-1]
Advertisement
Add Comment
Please, Sign In to add comment