Graphs in Python: Adjacency Matrix

Ashita Saxena
Analytics Vidhya
Published in
3 min readMay 31, 2020

--

HELLO EVERYONE!!

As we all know that Graph is as a kind of data structure that is basically used to connect various elements through a network.

In this article , you will learn about how to create a graph using adjacency matrix in python. Lets get started!!

1️⃣ GRAPHS:

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.

A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.

The above picture represents the graph having vertices and edges. But the question arrises :

How will you represent the graph in your code??

In order to answer the above question Adjacency Matrix comes into picture!

They give us a way to represent our graph following a very efficient and structured procedure. By creating a matrix (a table with rows and columns), you can represent nodes and edges very easily.

Let’s see how you can create an Adjacency Matrix for the given graph

Weighted Directed Graph

Let’s Create an Adjacency Matrix:

1️⃣ Firstly, create an Empty Matrix as shown below :

Empty Matrix

2️⃣ Now, look in the graph and staring filling the matrix from node A:

Since no edge is going from A to A, therefore fill 0 in the block.

A →A , value will be 0

A →B , value will be 2

A →C , value will be 0

A →D , value will be 1

A →E , value will be 0,

Repeat the same process for other vertices.

3️⃣ Replace all the 0 values with NULL.After completely filling the blocks, Matrix will look like as follows:

🏆 Finally! — Our Matrix is Ready!

💻Let’s Code!

Here is an example of an weighted directed graph represented with an Adjacency Matrix 👇

Adding Vertices and Edges

Code to print the Graph:

Let’s see how this code works behind the scenes:

1️⃣ ADD VERTICES:

With this part of code , you can add vertices to your matrix.

If the vertex that you are adding is already present, then print “already exist” else append the vertex to the graph.

2️⃣ ADD EDGES:

For adding edge between the 2 vertices, first check that whether the vertices are valid and exist in the graph or not.

After this, since this code is not restricted to directed and undirected graph, So you can add the edge to both the vertices v1 and v2.

3️⃣ Now print the graph to obtain the following output:

Final Output

In this way you can create Graphs in Python using Adjacency Matrices.👍

THANK YOU!!😊

--

--