Graph- DFS
What is a Graph?
A Graph is a collection of nodes (called vertices) connected by edges.
Graphs can be:
Undirected (edges have no direction) or
Directed (Digraph) (edges have a direction).
Graphs can be weighted (edges have weights/costs) or unweighted.
How to Represent a Graph in Computers?
Main ways to represent:
Adjacency Matrix:
A 2D array
G[V][V]
whereV
= number of vertices.G[i][j] = 1
if there is an edge between vertexi
andj
, else0
.Good for dense graphs.
Adjacency List:
An array of lists.
Each element (vertex) points to a list of vertices it is connected to.
Good for sparse graphs (uses less memory).
Algorithms for Graph Traversal
Two popular traversals:
Traversal | Meaning | Method |
---|---|---|
BFS (Breadth-First Search) | Visit neighbors level by level | Queue |
DFS (Depth-First Search) | Explore as deep as possible before backtracking | Stack or Recursion |
DFS (Depth-First Search) Algorithm
Idea / Intuition
-
DFS explores a graph as deeply as possible along each branch before backtracking.
-
Works like going into a maze: you follow a path until you hit a dead end, then backtrack and try another path.
Input: Graph, Starting Vertex
Output: Traverse graph deeply
Algorithm (Recursive way):
-
Mark the starting vertex as visited.
-
Process (visit) the vertex.
-
For each adjacent (unvisited) vertex:
-
Recursively apply DFS.
Non-Recursive DFS Algorithm (using Stack)
Input: Graph G
(adjacency matrix or list), starting vertex v
Output: Order of traversal
Algorithm:
-
Create an empty stack.
-
Push the starting vertex
v
onto the stack. -
Mark
v
as visited. -
While the stack is not empty:
-
Pop a vertex
u
from the stack. -
Process (visit) vertex
u
. -
For each adjacent vertex
w
ofu
(in reverse order if you want normal DFS order): -
If
w
is not visited: -
Push
w
onto the stack. -
Mark
w
as visited.
Example:
There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick vertices as per the insertion order.
Output: [0 1 2 3 4]Explanation: The source vertex s is 0. We visit it first, then we visit an adjacent.
Start at 0: Mark as visited. Output: 0
Move to 1: Mark as visited. Output: 1
Move to 2: Mark as visited. Output: 2
Move to 3: Mark as visited. Output: 3 (backtrack to 2)
Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 1, then to 0)
Not that there can be more than one DFS Traversals of a Graph.
Time Complexity Analysis
Let:
-
= number of vertices
-
= number of edges
Case 1: Adjacency Matrix Representation
-
For each vertex, we scan all other vertices in its row →
-
For vertices →
Case 2: Adjacency List Representation
-
Each vertex explored once →
-
Each edge explored once (in undirected, twice) →
-
Total complexity →
👉 Adjacency List is preferred for sparse graphs.
Space Complexity
-
Space for visited array:
-
Space for recursion/stack: worst-case
-
Total:
Comments
Post a Comment