Advertisement
HXXXXJ

210. Course Schedule II

Mar 27th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.22 KB | None | 0 0
  1.     func findOrder(_ numCourses: Int, _ prerequisites: [[Int]]) -> [Int] {
  2.         var res = [Int]()
  3.         var indegree = [Int: Int]()
  4.         //init indegree
  5.         for i in 0 ..< numCourses {
  6.             indegree[i] = 0
  7.         }
  8.         //get adjacency list
  9.         var adjList = [Int: [Int]]() // from count : to course list
  10.         for pair in prerequisites{
  11.             let next = pair[0]
  12.             let first = pair[1]
  13.             adjList[first, default : [Int]()].append(next)
  14.             indegree[next] = indegree[next]! + 1
  15.         }
  16.        
  17.         //get indegree == 0
  18.         var queue = [Int]()
  19.         for (course, ind) in indegree{
  20.             if ind == 0 {
  21.                 queue.append(course)
  22.                 // indegree[course] = nil
  23.             }
  24.         }
  25.        
  26.         while queue.count > 0 {
  27.             let curr = queue.removeFirst()
  28.             res.append(curr)
  29.             //visit cur
  30.             if let list = adjList[curr]{
  31.                 for next in list{
  32.                     indegree[next] = indegree[next]! - 1
  33.                     if indegree[next] == 0 {
  34.                         // indegree[next] = nil
  35.                         queue.append(next)
  36.                     }
  37.                 }
  38.             }
  39.         }
  40.         var circles = [[Int]]()
  41.         for (course, ind) in indegree{
  42.             if ind != 0 {
  43.                 var currList = [Int]()
  44.                 getCircle( course, adjList, &currList, &circles)
  45.                 break   //only find one circle
  46.             }
  47.         }
  48.         if res.count != numCourses {
  49.             print(circles)
  50.             return []
  51.         }
  52.         return res
  53.     }
  54.    
  55.    
  56.    
  57.     func getCircle(_ course : Int, _ adj : [Int : [Int]], _ currList: inout [Int], _ res: inout [[Int]]){
  58.         if currList.contains(course) {
  59.             res.append(currList)
  60.             return
  61.         }
  62.         currList.append(course)
  63.         if let list = adj[course] {
  64.             for next in list{
  65.                 getCircle( next, adj, &currList, &res)
  66.             }
  67.         }
  68.         currList.removeLast()
  69.     }
  70.  
  71.    
  72.    
  73.     let prerequisites = [[0,1],[1,2],[2,3],[3,1]]
  74.     let number = 4
  75.    
  76.     findOrder(number, prerequisites)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement