# Introduction to Adjacency List for Graphself.__wrap_b=(t,n,e)=>{e=e||document.querySelector(`[data-br="\${t}"]`);let a=e.parentElement,r=R=>e.style.maxWidth=R+"px";e.style.maxWidth="";let o=a.clientWidth,c=a.clientHeight,i=o/2-.25,l=o+.5,u;if(o){for(;i+1<l;)u=Math.round((i+l)/2),r(u),a.clientHeight===c?l=u:i=u;r(l*n+o*(1-n))}e.__wrap_o||(typeof ResizeObserver!="undefined"?(e.__wrap_o=new ResizeObserver(()=>{self.__wrap_b(0,+e.dataset.brr,e)})).observe(a):process.env.NODE_ENV==="development"&&console.warn("The browser you are using does not support the ResizeObserver API. Please consider add polyfill for this API to avoid potential layout shifts or upgrade your browser. Read more: https://github.com/shuding/react-wrap-balancer#browser-support-information"))};self.__wrap_b(":Rimr36:",1)

Graphs are an important data structure in computer science and are widely used to represent real-world relationships between objects. In this blog, we will be introducing a common way of representing graphs, known as an adjacency list.

## Introduction

An Adjacency list is a collection of nodes that have an edge over each other. The advantage of this list over a regular graph is that you can edit or remove nodes from it easily. You can also add additional edges between two nodes if needed by using the `add_edge` method on your list object or calling another method (such as `add_node()`).

## What is an Adjacency List?

It is a list that can be used to represent a graph. It is implemented as an array, with each element of the array representing a vertex in the graph. The elements of the array store the vertices that are adjacent to the vertex represented by the element. Each item contains two pieces of information:

• The first element of the array represents the number of neighbours (if any) surrounding it. While the second element holds its location in space, i.e., left/right/top/bottom etc.
• You may have noticed that there are some similarities between an adjacency list and a directed graph, where nodes connect only if they share an edge or have some kind of relationship with each other. However, unlike directed graphs where edges are always identified by numbers instead of text labels like A-B or 1->2->3->4->5. In contrast, undirected graphs don’t require such identification labels. Because all paths between two points are available simultaneously, without having any restrictions on how many paths could exist between them. Therefore, no restriction on how many paths exist.

## Features of an Adjacency List

Adjacency lists are a data structure that stores the relationship between vertices in a graph. The nodes in an adjacency list are referred to as vertices, and their neighbours are stored at the same level of abstraction (e.g., two adjacent vertices). They also allow you to add new edges or remove existing ones easily by simply adding or removing items from your list respectively.

Adjacent pairs are stored in sorted order so that you can easily find them when needed. This makes it easy for us to perform operations such as finding all paths between two vertices using their indices within these structures.

• An adjacency list only stores the edges of a graph, not the vertices, making it a space-efficient representation of a graph.
• It is also simple to implement and easy to modify.
• An adjacency list can be easily modified to store additional information about the edges in the graph, such as weights or labels.

It is a data structure that stores the set of all vertices that are adjacent in a graph. It has several advantages over other graph structures such as adjacency lists being more efficient in terms of storage and access.

Adjacency lists can also be used to store and retrieve data. In addition, they can be used to implement algorithms on graphs. Like the shortest path or topological ordering which requires numeric values (the distance between two vertices).

## Drawbacks of an Adjacency Lists

• Adjacency lists are one of the most common graphs. They have an O(n) time complexity, and they use memory to store their nodes.
• The size of an adjacency list is also very high. This means that if you want to store large amounts of data on your adjacency list. It will be slow because of the amount of memory used by each node in the graph.
• It is not efficient for finding the edges connecting a particular vertex. As we have to traverse the entire linked list to find the desired edge.
• Another disadvantage is that it is not easy to find the degree of a vertex in an adjacency list. As we have to count the number of edges in the corresponding linked list.

A graph is a collection of nodes and edges. Nodes are connected by edges, which can be directed or undirected. An edge is a connection between two nodes, where one node is called the source and the other one is called the target. Edges are often represented as lines on paper or screens, but they can also be visualized as arrows in space (e.g., in Google Earth).

An important concept to remember about graphs is that we can add more than one edge between two given vertices. Like this:

This means we have multiple paths connecting two vertices together. Also note that there may be multiple paths connecting two vertices if they share some common property (e.g., location).

Below is an example of a graph represented using an adjacency list:

Vertex 0: [1, 2]

Vertex 1: [0, 2]

The Vertex 2: [0, 1, 3]

And Vertex 3: [2]

In this example, the adjacency list for vertex 0 is [1, 2], which means that vertex 0 is connected to vertices 1 and 2. Similarly, the adjacency list for vertex 1 is [0, 2], which means that vertex 1 is connected to vertices 0 and 2.

## Example of an Adjacency List

Consider the following graph:

To represent this graph as list:

Vertex 0: [1, 2]

Vertex 1: [0, 2]

and Vertex 2: [1]

## Implementation of an Adjacency List

This can be implemented in several ways, such as using an array of linked lists or an array of sets. Below is an example of its implementation using an array of linked lists in Python:

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.shcb-language {
border: 0;
clip: rect(1px, 1px, 1px, 1px);
-webkit-clip-path: inset(50%);
clip-path: inset(50%);
height: 1px;
margin: -1px;
overflow: hidden;
position: absolute;
width: 1px;
word-wrap: normal;
word-break: normal;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```class Graph:
def __init__(self, num_vertices):
self.num_vertices = num_vertices
self.adjacency_list = [[] for _ in range(num_vertices)]

def print_graph(self):
print(f"Vertex {i}: {vertex}")

g = Graph(4)
g.print_graph()
```Code language: Python (python)```

The above code creates a graph with 4 vertices and 4 edges and adds the edges to the adjacency list using the `add_edge` function. The `print_graph` function is then used to print the adjacency list. The output of this code will be:

``````Vertex 0: [1, 2]
Vertex 1: [0, 2]
Vertex 2: [0, 1, 3]
Vertex 3: [2]```Code language: Python (python)```

## Conclusion

In summary, These lists are a simple and space-efficient way of representing a graph and are easy to modify and implement. However, it has some drawbacks, such as inefficiency in finding the edges of a particular vertex and difficulty in finding the degree of a vertex. It is important to choose the appropriate representation of a graph depending on the specific needs of the application.

## FAQs

### What is an adjacency list example?

It is a data structure that is used to represent a finite graph. It is a list of lists, where each list represents a vertex in the graph and contains the vertices that are adjacent to it.

Such as, consider the following graph:

### How do you represent an adjacency list?

Representation of the adjacency list shown in the above graph would be:

``````10 -> 20 -> 40
20 -> 10 -> 30
30 -> 20 -> 40
40 -> 10 -> 30```Code language: Python (python)```

### What is an adjacency list in C++?

To represent this in C++, you can use an array of linked lists.

``````#include <iostream>
#include <list>

using namespace std;

const int N = 5;

int main() {

return 0;
}```Code language: C++ (cpp)```

### Is an adjacency list an array?

No, It is a list of lists, not an array. It is an efficient representation of a graph when the graph is sparse. That is when it has a small number of edges compared to the number of vertices.

There are several advantages of using it, to represent a graph. First, it is easy to implement and requires only a small amount of memory. Second, it allows for efficient insertion and deletion of edges. Finally, it can be used to represent both directed and undirected graphs.

There are also some disadvantages to using it. First, it can be slower than other representations. Such as an adjacency matrix, when it comes to querying the graph. Second, it is not well-suited for dense graphs, that is, graphs with a large number of edges. Finally, it can be more difficult to implement some graph algorithms using an adjacency list compared to other representations.

### Sharing is caring

Did you like what Srishti Kumari wrote? Thank them for their work by sharing it on social media.

0/20000