 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
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]]
Advertisements
 