Graph Data Structure: Types, Representation, BFS and DFS

A graph is a set of vertices joined by edges. Learn the terminology, the main types of graph, adjacency matrix vs adjacency list with costs, BFS and DFS with working Python code, and five classic interview problems.

Graph data structure

Data structures are specialized formats that we use to store, process, and retrieve data according to our needs. There are several data structures that serve different purposes depending on the requirements; like the different types of utensils in our kitchen.

For example- We use bowls or cups for storing liquid items, plates won’t work in that case.

Similarly, in some cases, we need an array data structure, in some cases we need linked lists, and in some certain cases we need graphs.

Before we zone in on graph data structure, here are a few things we've covered earlier, in case you might want to learn:

Data Structures & Algorithms

Array Data Structure

Stack Data Structure

Queue Data Structure

Linked List Data Structure

Introduction to Graph

A graph is a non-linear data structure. It is a collection of nodes connected to each other by edges. Each node contains a data field.

Let's understand this with an example-

On Facebook, every profile is a node, including photos, videos, events, pages, and all other properties that have data.

And every connection acts as an edge, whether it’s between you and your Facebook friend or just a page you’ve liked.

Facebook and other social networks are just huge collections of nodes and edges.

Graph data structure solves many real-life problems. Most importantly they’re used to represent networks such as road networks in a city or circuit networks among other things.

A graph consists of-

  • A set of nodes, also known as vertices (V)
  • A set of edges (E), each connecting a pair of vertices and written as a pair such as (0, 1)
Graph with four vertices, 0 to 3, joined by four edges in a diamond shape: 0-1, 1-2, 2-3 and 3-0

V (Vertices) = {0, 1, 2, 3}

E (Edges) = {(0,1), (0,3), (1,2), (2,3)}

G (Graph) = {V, E}

Graph terminology

Vertex - Each node of a graph is called a vertex. (plural - vertices). In the image above, the dots represented by 0, 1, 2, and 3 are vertices.

Edge - Edges in a graph are the lines that connect two vertices. In the image above- the line (0, 1) from 0 to 1 represents an edge, similarly (1, 2), and so on.

Edges can be represented in the form of two-dimensional arrays.

Adjacency - A vertex is adjacent to another vertex if there is an edge connecting them. In the image above, vertices 0 and 1 are adjacent, but vertices 1 and 3 are not adjacent as there’s no edge between them.

Paths - A sequence of edges that takes you from one vertex to another, including vertices that are not adjacent to each other. In the above example: 1 and 3 are not adjacent. So, the sequence of edges [(1, 2), (2, 3)] will represent a path.

Path in graphs

Directed Graph - A graph in which an edge (0, 1) doesn't necessarily mean that there is an edge (1, 0) as well. An edge in a directed graph travels in only one direction. Arrows are used to represent that direction. (More on directed graphs later in the article)

A few more terms you will meet in the rest of this post:

TermMeaning
DegreeThe number of edges that touch a vertex. In a directed graph it splits into in-degree (edges coming in) and out-degree (edges going out).
WeightA number attached to an edge, such as a distance or a cost.
CycleA path that starts and ends at the same vertex.
Connected graphA graph in which there is a path between every pair of vertices.
Sparse and denseA sparse graph has far fewer edges than the maximum possible. A dense graph has close to the maximum, about V² edges for V vertices.
DAGA directed acyclic graph: a directed graph with no cycles.

Basic Operations in a Graph

Add/Remove Vertex

This is the most basic operation in a graph. You have to simply add a vertex to the graph; not needing to connect it with some other vertex through an edge.

While removing a vertex, you have to delete all the edges to and from that particular vertex.

Add/Remove Edge

This operation adds or removes an edge between two vertices. If all the edges originating from or ending at say vertex 1 is removed, 1 would become isolated.

All four operations on an adjacency list, in Python (the Java version appears later in this post):

class Graph:
    def __init__(self):
        self.adj = {}                              # vertex -> set of neighbours

    def add_vertex(self, v):
        self.adj.setdefault(v, set())

    def add_edge(self, a, b):                      # undirected edge
        self.add_vertex(a)
        self.add_vertex(b)
        self.adj[a].add(b)
        self.adj[b].add(a)

    def remove_edge(self, a, b):
        self.adj[a].discard(b)
        self.adj[b].discard(a)

    def remove_vertex(self, v):
        for neighbour in self.adj.pop(v, set()):   # delete every edge to and from v
            self.adj[neighbour].discard(v)

    def has_edge(self, a, b):
        return b in self.adj.get(a, set())


g = Graph()
for a, b in [(0, 1), (0, 3), (1, 2), (2, 3)]:      # the graph at the top of this post
    g.add_edge(a, b)
print(g.has_edge(1, 2), g.has_edge(1, 3))          # True False
g.remove_vertex(0)
print(sorted(g.adj[1]), sorted(g.adj[3]))          # [2] [2]
Breadth-first search on a graph with vertices 1 to 5: the traversal visits 1, then 2 and 3, then 4 and 5

This search operation traverses all the nodes at a single level/hierarchy before moving on to the next level of nodes. BFS algorithm starts at the first node (in this picture - 1) and traverses all the nodes adjacent to 1 i.e. 2 and 3. After all the nodes at the first level are traversed, it proceeds to the next level repeating the same process.

For example - After vertices 2 and 3 are traversed, the BFS algorithm will then move to the first adjacent node of 2 i.e. 4, and traverse all its adjacent nodes. This goes on until all the nodes in the graph are searched.

BFS keeps the discovered vertices in a queue, so the oldest one is explored first. That is why it works level by level, and why in an unweighted graph it finds the path with the fewest edges. Here is BFS on the graph from the picture, stored as an adjacency list:

from collections import deque

graph = {                      # adjacency list: vertex -> its neighbours
    1: [2, 3],
    2: [1, 4, 5],
    3: [1],
    4: [2],
    5: [2],
}

def bfs(graph, start):
    visited = {start}
    order = []
    queue = deque([start])
    while queue:
        vertex = queue.popleft()             # take the oldest discovered vertex
        order.append(vertex)
        for neighbour in graph[vertex]:
            if neighbour not in visited:     # never queue a vertex twice
                visited.add(neighbour)
                queue.append(neighbour)
    return order

print(bfs(graph, 1))   # [1, 2, 3, 4, 5]

Each vertex is queued once and each edge is looked at a constant number of times, so BFS takes O(V + E) time with an adjacency list, and O(V) extra space for the queue and the visited set.

Depth-first search

This algorithm traverses the nodes in a vertical fashion. It starts at a chosen vertex, follows one path as deep as it can, and only then backs up to try the next adjacent vertex.

Example - The algorithm will start with 1 and search all the nodes connected to 2 - 4 and 5, and then move to the next adjacent node to 1 i.e. 3. The order would be given as: 1 -> 2 -> 4 -> 5 -> 3.

DFS uses a stack, which a recursive function gets for free from the call stack (see how recursion works). The same graph, visited depth first:

def dfs(graph, start):
    visited, order = set(), []

    def visit(vertex):
        visited.add(vertex)
        order.append(vertex)
        for neighbour in graph[vertex]:
            if neighbour not in visited:
                visit(neighbour)             # go deeper before trying the next neighbour

    visit(start)
    return order

print(dfs(graph, 1))   # [1, 2, 4, 5, 3]

DFS also takes O(V + E) time with an adjacency list. It does not find shortest paths, but it is the base of topological sorting and of finding connected components. On a very deep graph, use an explicit stack instead of recursion to avoid a stack overflow.

BFSDFS
ExploresLevel by levelOne branch as deep as possible, then backs up
UsesA queueA stack or recursion
TimeO(V + E)O(V + E)
Good forFewest-edge paths in unweighted graphs, testing if a graph is bipartiteTopological sorting, connected components, exploring every route

Types of Graphs

Graphs are classified in several independent ways, so one graph can be several types at once. Here is the map before the diagrams:

Classified byTypes
Edge directionUndirected, directed (digraph)
Edge valuesUnweighted, weighted (labelled)
CyclesCyclic, acyclic (a DAG when it is directed)
ConnectivityConnected, disconnected
Repeated edgesSimple (no loops, no repeated edges), multigraph (repeated edges), pseudograph (loops and repeated edges)
Special shapesComplete, regular, bipartite, null, trivial
SizeFinite, infinite

Finite Graph

A finite Graph has a defined (countable) number of vertices and edges.

Finite Graph

If a graph G = (A, B) has a finite number of vertices A and edges B, it's a finite graph.

Infinite graph

Infinite Graph

As the name suggests, an infinite graph has an unlimited number of vertices and edges. It would still be represented as G = (A, B) but the values of both A and B would be infinite.

Trivial Graph

It's a graph with only one vertex, and therefore no edges.

Trivial Graph

Simple Graph

Simple Graph

A simple Graph is one in which there is at most one edge connecting a pair of vertices and no self-loops. (as shown in the image above). A railway track connecting two different cities is a perfect example of a simple Graph.

Multi Graph

Multi Graph

You search for a location in Google maps and it shows multiple paths taking you to the same location. That's a multi Graph in which more than one edge could be connecting two vertices.

Null Graph

Null Graph

In a null graph, no edges are there to connect the vertices, meaning, all the vertices are isolated.

Null graphs have a zero size.

Order in a graph - Number of vertices

Size - Number of edges

So, a null graph might have 'n' order but will be of 'zero' size.

Complete Graph

Complete Graph

In a complete graph, each vertex is adjacent to every other vertex, i.e. all the vertices in the graph are connected to each other. A complete graph with n vertices has n(n-1)/2 edges.

Pseudo Graph

Pseudo Graph

A pseudo Graph G = {A, B} contains a self-loop and multiple edges. In the above image, we have the vertices (1, 2, 3, 4) in which 1 and 2 have multiple edges between them and 2 also has a self-loop.

Regular Graph

Regular Graph

It's a regular graph if every node of the graph is connected to the same number of vertices.

Example: In a 2-regular Graph, each vertex is connected to two other vertices. Similarly, in a 3-regular graph, each vertex is adjacent to three other vertices.

Note: All complete graphs are regular graphs but all regular graphs are not necessarily complete graphs.

Bipartite Graph

Bipartite Graph

This one is a bit complicated. In a bipartite graph, the vertices are divided into two subsets (Set A and Set B), and all the edges connect a node from Set A to a node from Set B.

No edge will be connecting two nodes in the same set.

Let's make it more clear -

If we take two sets as A = {1, 2, 3, 4} and B = {5, 6, 7} then the vertices of Set A will only be connected with the vertices of Set B.

Labelled Graph

Labelled Graph

A labelled graph is the one in which the vertices and edges of a graph have a name, data, or weight attached to them. When the labels on the edges are numbers, such as distances or costs, it is called a weighted graph.

Directed Graph

Directed graph (digraph) with arrows showing the direction of each edge

A directed graph has edges that connect an ordered pair of vertices. If an edge is connecting a pair of vertices (1 and 2) from 1 to 2, the edge will have an arrow directed to 2. If we change the direction of the arrow, the meaning of the graph will change.

They are also known as Digraphs and are useful in marking hierarchies in social networks and roadways.

Connected & Disconnected Graphs

Connected Graph

If every pair of vertices (a, b) of a graph is reachable from one another, it can be called a connected graph. In other words, there needs to be at least one path between each and every pair of vertices for it to be a connected graph.

A connected graph with x number of vertices will have at least x-1 edges.

If at least one pair of vertices has no path between them, it is a disconnected graph.

Disconnected Graph

A null graph with two or more vertices and no edges is always a disconnected graph.

Cyclic Graph

Cyclic Graph

As the name suggests, the vertices and edges form a cycle in a cyclic graph. In a simple graph a cycle needs at least 3 vertices. The simplest case is a cycle graph, where n vertices (n>=3) are joined in a closed chain by exactly n edges.

Example - A graph G that consists of n vertices (n>=3) i.e. X1, X2, X3........Xn and edges (X1, X2), (X2, X3), (X3, X4)........(Xn, X1) will be a cyclic graph, since the last vertex Xn is also connected to X1.

Acyclic graph

Acyclic Graph

If there are no cycles present in a graph, it's an acyclic graph. If we start traversing the graph from point 2, we wouldn't have a path to traverse all the vertices and come back to point 2.

A connected undirected graph with no cycles is a tree, and a directed graph with no cycles is called a DAG (directed acyclic graph).

Representation of Graph

Let's say that we have to store a graph in the computer's memory. What technique will we use?

How will we represent the graph?

There are two major ways to do that:

  • Adjacency matrix (Sequential representation)
  • Adjacency list (Linked list representation)

We'll cover both of them one by one.

Adjacency matrix

An adjacency matrix is used to represent the mapping between vertices and edges of the graph. It can represent the undirected graph, directed graph, weighted undirected, and weighted directed graph. How?

Let's understand this with an undirected graph-

If there are n vertices in an undirected graph, the adjacency matrix for that graph will be n*n.

And each cell of the matrix will be denoted by either 0 or 1 depending upon the existence of the edge between two nodes.

So, any matrix adj[a][b] will denote the edges between vertex a and vertex b.

This matrix will be 1 if there exists an edge between the two nodes, else it will be 0.

  • Xab = 1 (if there is an edge from a to b)
  • Xab = 0 (if there is no edge between the two vertices)

If there is no self-loop present in the graph, the diagonal entries will be 0.

Adjacency Matrix

The image shows the mapping among the vertices (a, b, c, d, e).

You'll find that the cross between a and a, or b and b says 0, that means there's no self loop.

Also, the cross between A*B and B*A says 1, which means it's an undirected graph

Activity: Match the binary values in the adjacency matrix with the edges in the graph. If the matrix for a particular pair says 0; there is no edge between the pair.

The adjacency matrix for a directed graph is different. The entry for Xab will be 1 only when there is an edge from vertex a to vertex b.

(Learn more about adjacency matrix representation here)

Adjacency list

Adjacency list uses linked lists to represent a graph. For each node in a graph, there exists a linked list that stores the node value and a pointer to the next adjacent node.

Adjacency list

In the image, we can see that there is a linked list for every node in the graph. Vertex a is connected to both vertex b , and vertex d, as you can see in the adjacency list representing the graph.

Adjacency matrix vs adjacency list

Here are both representations of the graph from the top of this post, built from its edge list in Python. The adjacency list is a dictionary (a hash map) from each vertex to its neighbours:

edges = [(0, 1), (0, 3), (1, 2), (2, 3)]      # the graph at the top of this post
n = 4

matrix = [[0] * n for _ in range(n)]          # adjacency matrix: n x n grid of 0 and 1
for a, b in edges:
    matrix[a][b] = matrix[b][a] = 1           # undirected: fill both cells

adj = {v: [] for v in range(n)}               # adjacency list: vertex -> neighbours
for a, b in edges:
    adj[a].append(b)
    adj[b].append(a)

print(matrix)   # [[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]
print(adj)      # {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2]}

The two trade memory for lookup speed:

Adjacency listAdjacency matrix
MemoryO(V + E)O(V²)
Add an edgeO(1)O(1)
Is there an edge between x and y?O(V) in the worst case (scan x's neighbours)O(1)
Visit every vertex with BFS or DFSO(V + E)O(V²)
Better forSparse graphsDense graphs, or when you need constant-time edge checks

As a rule of thumb, start with an adjacency list. Switch to a matrix when the graph is dense, or when you check for individual edges far more often than you walk through neighbours.

Java implementation of graphs

Let's create a Java program to implement a graph. It stores the graph as an adjacency list: a HashMap from each vertex to a LinkedList of its neighbours.

import java.util.*;
class Graph<T>
{
    //creating an object of the Map class that stores the edges of the graph
    private Map<T, List<T> > map = new HashMap<>();
    //the method adds a new vertex to the graph
    public void addNewVertex(T s)
    {
        map.put(s, new LinkedList<T>());
    }
    //the method adds an edge between source and destination
    public void addNewEdge(T source, T destination, boolean bidirectional)
    {
        //
        if (!map.containsKey(source))
            addNewVertex(source);
        if (!map.containsKey(destination))
            addNewVertex(destination);
        map.get(source).add(destination);
        if (bidirectional == true)
        {
            map.get(destination).add(source);
        }
    }
    //the method counts the number of vertices
    public void countVertices()
    {
        System.out.println("Total number of vertices: "+ map.keySet().size());
    }
    //the method counts the number of edges
    public void countEdges(boolean bidirection)
    {
        //variable to store number of edges
        int count = 0;
        for (T v : map.keySet())
        {
            count = count + map.get(v).size();
        }
        if (bidirection == true)
        {
            count = count / 2;
        }
        System.out.println("Total number of edges: "+ count);
    }
    //checks a graph has vertex or not
    public void containsVertex(T s)
    {
        if (map.containsKey(s))
        {
            System.out.println("The graph contains "+ s + " as a vertex.");
        }
        else
        {
            System.out.println("The graph does not contain "+ s + " as a vertex.");
        }
    }
    //checks a graph has edge or not
    //where s and d are the two parameters that represent source(vertex) and destination (vertex)
    public void containsEdge(T s, T d)
    {
        if (map.get(s).contains(d))
        {
            System.out.println("The graph has an edge between "+ s + " and " + d + ".");
        }
        else
        {
            System.out.println("There is no edge between "+ s + " and " + d + ".");
        }
    }
    //prints the adjacency list of each vertex
    //here we override the toString() method of the Object class
    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder();
        //foreach loop that iterates over the keys
        for (T v : map.keySet())
        {
            builder.append(v.toString() + ": ");
            //foreach loop for getting the vertices
            for (T w : map.get(v))
            {
                builder.append(w.toString() + " ");
            }
            builder.append("\n");
        }
        return (builder.toString());
    }
}
//creating a class in which we have implemented the driver code
public class GraphImplementation
{
    public static void main(String args[])
    {
        //creating an object of the Graph class
        Graph<Integer> graph = new Graph<>();
        //adding edges to the graph
        graph.addNewEdge(0, 1, true);
        graph.addNewEdge(0, 4, true);
        graph.addNewEdge(1, 2, true);
        graph.addNewEdge(1, 3, true);
        graph.addNewEdge(1, 4, true);
        graph.addNewEdge(2, 3, true);
        graph.addNewEdge(2, 4, true);
        graph.addNewEdge(3, 0, true);
        graph.addNewEdge(2, 0, true);
        //prints the adjacency list that represents the graph
        System.out.println("Adjacency List for the graph:\n"+ graph.toString());
        //counts the number of vertices in the graph
        graph.countVertices();
        //counts the number of edges in the graph
        graph.countEdges(true);
        //checks whether an edge is present or not between the two specified vertices
        graph.containsEdge(3, 4);
        graph.containsEdge(2, 4);
        //checks whether vertex is present or not
        graph.containsVertex(3);
        graph.containsVertex(5);
    }
}

Output:

Adjacency List for the graph:
0: 1 4 3 2
1: 0 2 3 4
2: 1 3 4 0
3: 1 2 0
4: 0 1 2

Total number of vertices: 5
Total number of edges: 9
There is no edge between 3 and 4.
The graph has an edge between 2 and 4.
The graph contains 3 as a vertex.
The graph does not contain 5 as a vertex.

Note that countEdges(true) divides the total by 2, which is only right when every edge is bidirectional, as it is in this example. For a graph with one-way edges, count them without dividing.

Applications of Graph

Graphs show up wherever the data is about connections. This is a short tour; the guide to the applications of graph data structure has the full list.

Real-world applications

Social networks - This is one of the most basic applications of a graph. A social graph illustrates connections among people and organizations in a social network. Example: Facebook

Biological networks - Brain networks and food chains can be modelled as graphs, with neurons or species as vertices and the links between them as edges.

Networks in molecular biology

Web graph - World Wide Web is another huge graph data set where all the documents are connected to each other using hyperlinks. In this case, these hyperlinks can be considered edges.

Road networks and navigation - Navigation is a graph problem. Junctions are vertices and roads are edges, often weighted by distance or travel time, and a shortest-path algorithm finds a route from point A to point B. You will see roads drawn as vertices and edges in apps like Google Maps, Uber and Waze.

Product recommendation - Recommendation systems can model users and products as a graph, with an edge between a user and every product they bought. Products bought by people who share your purchases then become candidates to recommend.

Blockchains - Each block in a blockchain contains a cryptographic hash of the previous block. Drawn as a graph, the blocks are vertices and those references are the edges.

Blockchain drawn as a graph: blocks are vertices, each linked to the block before it

In Computer Science

  • Graphs define the flow of computation. A control flow graph, originally developed by Frances E. Allen, acts as the graphical representation of computation during the execution of programs
  • Graphs represent networks of communication.
  • To represent data organization
  • Operating systems use resource allocation graphs to understand the state of the system. Here, each resource and process are represented as vertices, and edges connect the resources to the allocated process.

When to use a graph (and when not to)

Your data is...UseWhy
Connections that can run between any items: friends, roads, links, dependenciesA graphEdges can join any two vertices, with cycles, directions and weights
A hierarchy where every item has one parent, such as folders or an org chartA tree (a graph with no cycles)Simpler: there is exactly one path between any two nodes
A sequence in a fixed orderAn array or linked listPosition matters, not connections
Values you look up by a keyA hash mapO(1) access on average

Classic graph interview problems

Most graph questions are BFS or DFS with a twist. The hard part is seeing the graph, which is often hidden in a grid, a list of prerequisites or a set of words.

ProblemHow the graph shows up, and the approach
Number of IslandsEach land cell is a vertex joined to its land neighbours. Run DFS or BFS from every unvisited land cell and count how many times you start.
Clone GraphTraverse with BFS or DFS and keep a hash map from each original node to its copy, so no node is copied twice.
Course ScheduleCourses are vertices and prerequisites are directed edges. All courses can be finished only if the graph has no cycle. Check with DFS or topological sorting.
Is Graph Bipartite?Colour a start vertex, then give every neighbour the opposite colour with BFS or DFS. If an edge joins two vertices of the same colour, the answer is no.
Shortest Path in Binary MatrixRun BFS from the top-left cell, moving in eight directions. The first time you reach the bottom-right cell, the step count is the shortest path.

Final thoughts

You just learned about the graph data structure, its types, how to store it and how to traverse it. The pattern to remember: model the relationships as vertices and edges, store them as an adjacency list unless the graph is dense, and use BFS or DFS to explore.

In the words of Linus Torvalds, the main developer behind the Linux operating system:

“Bad programmers worry about the code. Good programmers worry about data structures and their relationships.”

If you want the core of data structures and algorithms in one place, this article is a good starting point. Then practise: graphs build on the rest of the series, since a queue drives BFS, a stack or recursion drives DFS, adjacency lists are hash maps of lists and a tree is a graph with no cycles.

Frequently asked questions

What is a graph in data structure?

A graph is a non-linear data structure made of vertices (nodes) and edges that join pairs of vertices. It models relationships such as friendships, roads and web links. Edges can be directed or undirected and can carry weights.

What are the types of graphs?

Graphs are classified by edge direction (directed or undirected), edge values (weighted or unweighted), cycles (cyclic or acyclic), connectivity (connected or disconnected) and special shapes such as complete, regular and bipartite graphs. Each type is shown with a diagram above.

What is the difference between a graph and a tree?

A tree is a connected graph with no cycles. With n vertices it has exactly n - 1 edges, and there is exactly one path between any two vertices. A general graph can have cycles, can be disconnected or directed, and has no root vertex.

What is the difference between BFS and DFS?

BFS visits vertices level by level using a queue and finds the path with the fewest edges in an unweighted graph. DFS follows one branch as deep as it can using a stack or recursion. Both take O(V + E) time with an adjacency list.

Should I use an adjacency matrix or an adjacency list?

Use an adjacency list for sparse graphs: it needs O(V + E) memory. Use an adjacency matrix for dense graphs, or when you must check for a single edge in constant time, at the cost of O(V²) memory.

×

Our Courses

Practice-Based Learning Tracks, Supercharged By A.I.