Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
- guard (prerequisites.count > 0) else {return true}
- var graph : [[Int]] = Array(repeating: [], count: numCourses + 1 )
- var inDegree : [Int] = Array(repeating: 0, count: numCourses + 1 )
- for x in prerequisites {
- graph[x[0]] += [x[1]]
- inDegree[x[0]] += 1
- }
- for course in graph.enumerated() {
- print ("To finish course \(course.offset) you must have finished \(course.element)")
- }
- for course in (inDegree.enumerated()) {
- print ("Course \(course.offset) needs \(course.element) courses to be complete")
- }
- var outputArr = [Int]()
- while let currentVertexIndx = (inDegree.enumerated().first { $0.element == 0 }?.offset) {
- outputArr.append( currentVertexIndx )
- for course in graph.enumerated() {
- if (course.element.contains(currentVertexIndx)) {
- inDegree[ course.offset ] -= 1
- }
- }
- inDegree[currentVertexIndx] = -1
- }
- return outputArr.count - 1 == numCourses
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement