You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
traverse all course in the queue, and delete one one prerequist for other courses
when there is still course left in the queue but no
use a degree array and a map for storing the graph
class A: degree = 0 | {A, [B, C, D, E]}
when pop A, all BCDE's degree need to be reduced.
importnumpyasnpclassSolution:
defcanFinish(self, numCourses: int, prerequisites: List[List[int]]) ->bool:
ifnot(prerequisites):
returnTrue# left: number of prereqs, right: next coursecourse_num_pre=np.zeros(numCourses)
course_dict=defaultdict(lambda: [])
course_deque=deque()
count=0forone_courseinprerequisites:
pre_course, next_course=one_course[1], one_course[0]
# add a pre to the next coursecourse_num_pre[next_course] +=1course_dict[pre_course].append(next_course)
# add initial values to queue when no prereqforiinrange(numCourses):
ifcourse_num_pre[i] ==0:
course_deque.append(i)
while(course_deque):
course_i=course_deque.popleft()
count+=1# reduce one prereq from each of next course# from the dict [course1, course2]fornext_coursein (course_dict[course_i]):
course_num_pre[next_course] -=1ifcourse_num_pre[next_course] ==0:
course_deque.append(next_course)
returncount==numCourses