- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to reverse the directed graph in Python

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 −

## Example

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))

## Input

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

## Output

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

- Related Articles
- Python Program for Detect Cycle in a Directed Graph
- Program to find largest color value in a directed graph in Python
- C++ Program to Check the Connectivity of Directed Graph Using BFS
- C++ Program to Check the Connectivity of Directed Graph Using DFS
- Connectivity in a directed graph
- Directed Acyclic Graph (DAG)
- Detect Cycle in a Directed Graph
- Euler Circuit in a Directed 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
- Longest Path in a Directed Acyclic Graph
- Shortest Path in a Directed Acyclic Graph
- C++ Program to Check if a Directed Graph is a Tree or Not Using DFS
- C++ Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph

Advertisements