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.py488 chars17 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.
gistlibby LogSnag