2192. All Ancestors of a Node in a Directed Acyclic Graph

Tapan RachchhTapan Rachchh
1 min read
class Solution:
    def getAncestors(self, n: int, edges: List[List[int]]) -> List[List[int]]:
        visited = set()
        adjList = defaultdict(set)
        parents = defaultdict(set)

        # Create adjacency list
        for (a, b) in edges:
            adjList[a].add(b)

        print('adjList', adjList)

        def dfs(i, p):
            if i not in visited:
                parents[i] = parents[i].union(p)
                p.add(i)
                for e in adjList[i]:
                    dfs(e, p)
                p.remove(i)
                visited.add(i)

        # Traverse through graph
        for i in range(n):
            visited = set()
            dfs(i, set([]))

        ans = []
        for i in range(n):
            ans.append(sorted(parents[i]))

        return ans
0
Subscribe to my newsletter

Read articles from Tapan Rachchh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tapan Rachchh
Tapan Rachchh