python | topological traversal approach | with notes
\nclass Solution:\n    """\n    we can use a bfs based approach to get the required ancestors for each node nodes\n    nodes with indegree of 0 will have empty 
```\nclass Solution:\n    """\n    we can use a bfs based approach to get the required ancestors for each node nodes\n    nodes with indegree of 0 will have empty ancestors list\n    then we will put all nodes with no incoming edges in queue\n    until the queue is empty:\n        pop the node\n        for all neighbors of node:\n            add the ancestor set of node along with the node in the ancestor set of neighbor\n    """\n    def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n        graph = {node: set() for node in range(n)}\n        indegree = {node: 0 for node in range(n)}\n        ans = [set() for _ in range(n)]\n        for edge in edges:\n            graph[edge[0]].add(edge[1])\n            indegree[edge[1]]+=1\n        nodes_with_no_incoming_edges = []\n        for node, indeg in indegree.items():\n            if indeg == 0:\n                nodes_with_no_incoming_edges.append(node)\n        while len(nodes_with_no_incoming_edges):\n            node = nodes_with_no_incoming_edges.pop()\n            for neighbor in graph[node]:\n                ans[neighbor].add(node)\n                ans[neighbor] = ans[neighbor].union(ans[node])\n                indegree[neighbor]-=1\n                if indegree[neighbor] == 0:\n                    nodes_with_no_incoming_edges.append(neighbor)\n                    \n        sorted_ans = []           \n        for ancestor in ans:\n            temp = sorted(list(ancestor))\n            sorted_ans.append(temp)\n        return sorted_ans\n```
['Topological Sort', 'Python']