How To Print An Adjacency Matrix In Python

In this tutorial, we will learn how to print an adjacency matrix in Python. An adjacency matrix is a square matrix used to represent a finite graph. The elements in the matrix indicate whether pairs of vertices are adjacent or not in the graph.

Adjacency matrices are beneficial in graph theory and computer science for representing and working with graphs. In particular, we will be using a NumPy array to create and print the adjacency matrix.

Step 1: Install NumPy

NumPy is a popular library in Python that provides support for large arrays and matrices, along with various mathematical functions to operate on these arrays. If you don’t have NumPy installed, you can install it using pip:

Step 2: Generate a Graph

To create an adjacency matrix, we first need to generate a graph. In this example, we will generate a simple undirected graph with 5 vertices and the following edges:

(0, 1)
(1, 2)
(1, 3)
(2, 3)
(2, 4)

To represent this graph, we will store the edges in a list called graph_edges:

Step 3: Create the adjacency matrix

Next, we will define a function called create_adjacency_matrix that takes the number of vertices and a list of edges as input and returns a NumPy array representing the adjacency matrix of the graph.

This function initializes a square matrix of zeros with dimensions determined by the number of vertices. It then iterates through each edge in the edge_list and sets the corresponding elements in the adjacency matrix to 1, indicating adjacency between the vertex pairs.

Step 4: Print the adjacency matrix

Finally, we can create the adjacency matrix and print it using the NumPy print function.

Full Code

Output

The adjacency matrix is:
[[0 1 0 0 0]
 [1 0 1 1 0]
 [0 1 0 1 1]
 [0 1 1 0 0]
 [0 0 1 0 0]]

Conclusion

In this tutorial, you have learned how to create and print an adjacency matrix in Python using the NumPy library.

You can now use this knowledge to represent and work with graphs, such as finding adjacent vertices, performing graph traversals, and implementing graph algorithms.