- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

- ans := a list of n different lists, where n is number of vertices
- for each index i, and adjacent list l in graph, do
- for each x in l, do
- insert i at the end of ans[x]

- for each x in l, do
- return ans

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],[4],[4],[1,2],[3]] print(ob.solve(graph))

[[1,2],[4],[4],[1,2],[3]]

[[], [0, 3], [0, 3], [4], [1, 2]]

- Related Questions & Answers
- Python Program for Detect Cycle in a Directed Graph
- Directed Acyclic Graph (DAG)
- Connectivity in a directed graph
- C++ Program to Check the Connectivity of Directed Graph Using DFS
- C++ Program to Check the Connectivity of Directed Graph Using BFS
- Detect Cycle in a Directed Graph
- Euler Circuit in a Directed Graph
- Longest Path in a Directed Acyclic Graph
- Shortest Path in a Directed Acyclic Graph
- C++ Program to Check Whether a Directed Graph Contains a Eulerian Cycle
- C++ Program to Check Whether a Directed Graph Contains a Eulerian Path
- C++ Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
- C++ Program to Check if a Directed Graph is a Tree or Not Using DFS
- C++ Program to Generate a Random Directed Acyclic Graph DAC for a Given Number of Edges
- C++ Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph

Advertisements