Leetcode 207 Course Schedule, leetcodeschedule
There are a totalNCourses you have to take, labeled from0
Ton - 1
.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair:[0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
For example:
2, [[1,0]]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0. So it is possible.
2, [[1,0],[0,1]]
There are a total of 2 courses to take. To take course 1 you shoshould have finished course 0, and to take course 0 you shoshould also have finished course 1. So it is impossible.
Topology Sorting: maintains a set of 0 inputs. First, place all the vertices with an inbound degree of 0, one by one lead to the points that can be reached by this origin point and delete the origin point. If the destination point is deleted from this origin point to its path, the inbound level is 0, put the vertex in the set.
Pseudocode
L ← Empty list that will contain the sorted elementsS ← Set of all nodes with no incoming edgeswhile S is non-empty do remove a node n from S add n to tail of L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into Sif graph has edges then return error (graph has at least one cycle)else return L (a topologically sorted order)
require 'set'def can_finish(num_courses, prerequisites) graph, neighbour = Hash.new{|hsh,key| hsh[key] = Set.new}, Hash.new{|hsh,key| hsh[key] = Set.new} prerequisites.each {|x,y| graph[x] << y; neighbour[y] << x} zero_degree, count = [], 0 num_courses.times {|x| zero_degree << x if graph[x].empty?} while not zero_degree.empty? node = zero_degree.pop count += 1 neighbour[node].each do |x| graph[x] -= [node] zero_degree << x if graph[x].empty? end end count == num_coursesend