Graphs in Python: Adjacency Matrix
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
Let’s Create an Adjacency Matrix:
1️⃣ Firstly, create an Empty Matrix as shown below :
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 👇
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:
In this way you can create Graphs in Python using Adjacency Matrices.👍