Suppose we have a directed graph, we have to find its reverse so if an edge goes from u to v, it now goes from v to u. Here input will be an adjacency list, and if there are n nodes, the nodes will be (0, 1, ..., n-1).
So, if the input is like
then the output will be
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, graph): ans = [ for _ in graph] for i, l in enumerate(graph): for x in l: ans[x].append(i) return ans ob = Solution() graph = [[1,2],,,[1,2],] print(ob.solve(graph))
[, [0, 3], [0, 3], , [1, 2]]