DFS & BFS Blog
DFS & BFS Blog
● What’s a graph?
○ A graph is a pictorial representation of a set of objects where some pairs
of objects are connected by links.
Examples:
● Graph Components:
○ Any graph has two major components:
■ Nodes (Vertices):
● The objects that we want
to describe a connection
between them.
● Vanya, Alex, Sam and
Jan are considered
nodes.
■ Edges:
● The links that connect nodes.
● Represented by an arrow or a line.
● Presence of an edge between two nodes implies that a
connection exists between them.
● There are three types of edges:
○ Undirected Edge.
○ Directed Edge.
○ Weighted Edge.
● Types of Edges:
Examples
● Tree
A tree is an undirected graph where any two vertices are connected by exactly
one path.
1) Adjacency Matrix.
2) Adjacency List.
● Adjacency matrix:
An adjacency list represents a graph as an array of lists. The index of the array
represents a vertex and each element in its list represents the other vertices that
form an edge with the vertex.
Space complexity
Searching for an edge You will just check if You have to iterate over
graph[node1][node2]=1 all the components of
or not so it takes O(1) graph[node] so it takes
O(|E|)
The DFS is a recursive algorithm that uses the idea of backtracking. It goes as
deep into the graph as possible and backtracks once there are no unvisited
vertices left.
First, we choose a vertex to start from it, then the steps go:
This way, we visit all vertices that are reachable from the starting vertex.
BFS is a traversing algorithm where you should traverse the graph as levels
where you move horizontally and visit all the nodes of the current level, then you
move to the next layer and so on.
First, we choose a vertex to start from, add it to a queue, and mark it as a visited
vertex. Note that the starting vertex is in level 0.
● Every time our current vertex will be at the front of the queue, search for
an unvisited vertex from its neighbors.
● If we didn’t find any unvisited neighbor, we do nothing otherwise; we mark
it as a visited vertex, then we add it to the queue. (this step is repeated till
all the unvisited neighbors are added to the queue)
● The new vertex added to the queue is at the next level of the current
vertex, so its level will be the current vertex level incremented by 1.
● Pop the queue’s front and repeat the same steps we did above until the
queue becomes empty.
Time Complexity: where V is the number of vertices and E is the
number of edges.