Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to calculate vertex-to-vertex reachablity matrix in Python
A vertex-to-vertex reachability matrix is a 2D matrix that shows whether there is a path between any two vertices in a graph. For a graph with n vertices, we create an n×n matrix M where:
M[i, j] = 1 when there is a path between vertices i and j
M[i, j] = 0 otherwise
Problem Example
Given a graph represented as an adjacency list, we need to find the reachability matrix. Consider this graph:
The expected reachability matrix will be:
| From/To | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | 1 | 1 |
| 1 | 0 | 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 1 | 1 | 1 |
| 3 | 0 | 1 | 1 | 1 | 1 |
| 4 | 0 | 1 | 1 | 1 | 1 |
Algorithm
We use Breadth-First Search (BFS) from each vertex to find all reachable vertices ?
Create an n×n matrix filled with zeros
For each vertex i, perform BFS to find all reachable vertices
Mark reachable vertices as 1 in the matrix
Return the completed matrix
Implementation
class Solution:
def solve(self, graph):
n = len(graph)
ans = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
q = [i]
while q:
node = q.pop(0)
if ans[i][node]:
continue
ans[i][node] = 1
neighbors = graph[node]
for neighbor in neighbors:
q.append(neighbor)
return ans
# Test the solution
ob = Solution()
adj_list = [[1,2],[4],[4],[1,2],[3]]
result = ob.solve(adj_list)
print("Reachability Matrix:")
for row in result:
print(row)
Reachability Matrix: [1, 1, 1, 1, 1] [0, 1, 1, 1, 1] [0, 1, 1, 1, 1] [0, 1, 1, 1, 1] [0, 1, 1, 1, 1]
How It Works
For the adjacency list [[1,2],[4],[4],[1,2],[3]]:
Vertex 0: Can reach vertices 1, 2, 4, and 3 (through paths)
Vertex 1: Can reach vertex 4, then 3, then 1 and 2
Vertex 2: Can reach vertex 4, then 3, then 1 and 2
Vertex 3: Can reach vertices 1 and 2, then 4
Vertex 4: Can reach vertex 3, then 1 and 2
Time and Space Complexity
Time Complexity: O(V × (V + E)) where V is vertices and E is edges
Space Complexity: O(V²) for the result matrix
Conclusion
The reachability matrix efficiently represents vertex connectivity using BFS traversal. This approach works well for directed graphs and provides a clear overview of all possible paths between vertices.
