create adjacency matrix in python

To create an adjacency matrix in Python, you can first create an empty matrix with rows and columns equal to the number of vertices in your graph. Then, you can iterate through each edge in the graph and update the corresponding cells in the matrix to indicate that the two vertices are connected.

Here's an example code snippet to create an adjacency matrix for a graph:

main.py
# example graph represented as a list of edges
graph = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 3)]

# determine number of vertices in the graph
num_vertices = max(max(edge) for edge in graph) + 1

# create empty adjacency matrix
adj_matrix = [[0] * num_vertices for _ in range(num_vertices)]

# populate adjacency matrix by iterating through edges
for edge in graph:
    v1, v2 = edge
    adj_matrix[v1][v2] = 1
    adj_matrix[v2][v1] = 1 # uncomment for undirected graph

print(adj_matrix)
488 chars
17 lines

In this example, the graph variable represents a list of edges in the graph. Each edge is a tuple of two vertices that it connects. The code determines the number of vertices in the graph by finding the maximum vertex index in the edge list and adding 1. It then creates an empty matrix of the appropriate size using a list comprehension. Finally, it iterates through each edge in the graph and sets the corresponding cells in the adjacency matrix to 1 to indicate that the vertices are connected. Note that if your graph is undirected, you will need to uncomment the second adj_matrix assignment to set the reverse edge as well.

related categories

gistlibby LogSnag