Graphs - BFS
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 |
BFS (Breadth-First Search) Algorithm
Idea / Intuition
-
BFS explores a graph level by level (breadth-wise).
-
It visits all neighbors of a vertex before going deeper.
👉 BFS uses a queue to ensure nodes are processed in the order they are discovered.
Input: Graph, Starting Vertex
Output: Traverse graph level-wise
Algorithm:
-
Create a queue and enqueue the starting vertex.
-
Mark the starting vertex as visited.
-
While the queue is not empty:
-
Dequeue a vertex and process it.
-
Enqueue all its adjacent (unvisited) vertices.
-
Mark them as visited.
Example:
Output: [0, 1, 2, 3, 4]
Explanation: Starting from 0, the BFS traversal will follow these steps:
Visit 0 → Output: [0]
Visit 1 (first neighbor of 0) → Output: [0, 1]
Visit 2 (next neighbor of 0) → Output: [0, 1, 2]
Visit 3 (next neighbor of 1) → Output: [0, 1, 2, 3]
Visit 4 (neighbor of 2) → Final Output: [0, 1, 2, 3, 4]
Time Complexity Analysis
Let:
-
= number of vertices
-
= number of edges
Case 1: Adjacency Matrix Representation
-
For each vertex, check all other vertices →
-
For all vertices → .
Case 2: Adjacency List Representation
-
Each vertex enqueued/dequeued once → .
-
Each edge examined once (undirected, twice) → .
-
Total complexity → .
👉 Adjacency list is more efficient for sparse graphs.
Space Complexity
-
Space for visited array: .
-
Space for queue: up to in worst case.
-
Total: .
Comments
Post a Comment