Swift Topological Sort
This is a classical Topolical sort problem. \n Build graph from edges\n Start with all nodes u which don\'t have any incoming edges\n Visit all children of node
This is a classical Topolical sort problem. \n* Build `graph` from `edges`\n* Start with all nodes `u` which don\'t have any incoming edges\n* Visit all children of node `u`, for each child `v`, insert `u` as well as `ancestors[u]` as ancestors of `v`. We need to use `Set` to avoid any duplication\n* Repeat until we\'ve already processed all nodes \n* Go over each node and sort the list of ancestors as per the problem statement\n\n**Swift**\n```swift\nclass Solution {\n  func getAncestors(_ n: Int, _ edges: [[Int]]) -> [[Int]] {\n    var graph = [Int: [Int]]()\n    var inDegree = Array(repeating: 0, count: n)\n    for edge in edges {\n      let (u, v) = (edge[0], edge[1])\n      graph[u, default: []].append(v)\n      inDegree[v] += 1\n    }\n    \n    var ancestors = Array(repeating: Set<Int>(), count: n)\n    var stack = [Int]()\n    for u in 0..<n where inDegree[u] == 0 {\n      stack.append(u)\n    }\n    \n    while !stack.isEmpty {\n      let u = stack.removeLast()\n      for v in graph[u, default: []] {\n        inDegree[v] -= 1 \n        if inDegree[v] == 0 {\n          stack.append(v)\n        }\n          \n        ancestors[v].insert(u)\n        ancestors[v].formUnion(ancestors[u])\n      }\n    }\n    \n    var res = [[Int]]()\n    for u in 0..<n {\n      res.append(ancestors[u].sorted())\n    }\n    \n    return res\n  }\n}\n```
['Graph', 'Topological Sort', 'Swift']