Data Structure and Algorithms - BFS and DFS
Data Structure and Algorithms - BFS and DFS
Structure
A graph is an abstract data type (ADT) that consists of a set of
objects that are connected to each other via links. These objects
are called vertices and the links are called edges.
Operations of Graphs
The primary operations of a graph include creating a graph with
vertices and edges, and displaying the said graph. However, one
of the most common and popular operation performed using
graphs are Traversal, i.e. visiting every vertex of the graph in a
specific order.
The DFS traversal uses the stack data structure to keep track of
the unvisited nodes.
Breadth First Search Traversal
The DFS traversal uses the queue data structure to keep track of
the unvisited nodes.
Representation of Graphs
While representing graphs, we must carefully depict the elements
(vertices and edges) present in the graph and the relationship
between them. Pictorially, a graph is represented with a finite set
of nodes and connecting links between them. However, we can
also represent the graph in other most commonly used ways, like
−
Adjacency Matrix
Adjacency List
Adjacency Matrix
The Adjacency Matrix is a V×V matrix where the values are filled
with either 0 or 1. If the link exists between Vi and Vj, it is
recorded 1; otherwise, 0.
Adjacency List
The adjacency list is a list of the vertices directly connected to the
other vertices in the graph.
Types of graph
There are two basic types of graph −
Directed Graph
Undirected Graph
Undirected Graph
Spanning Tree
A spanning tree is a subset of an undirected graph that contains
all the vertices of the graph connected with the minimum number
of edges in the graph. Precisely, the edges of the spanning tree is
a subset of the edges in the original graph.
Properties
Example
Shortest Path
The shortest path in a graph is defined as the minimum cost route
from one vertex to another. This is most commonly seen in
weighted directed graphs but are also applicable to undirected
graphs.