09.tutorial - Graph Traversals
09.tutorial - Graph Traversals
We will focus on Breadth-First Search (BFS) and Depth-First Search (DFS), using the
Adjacency Matrix representation of graphs.
Learning Goals
● Implement DFS and BFS traversal algorithms in C using an adjacency matrix.
● Solve simple problems using graph traversal techniques.
● Understand the difference between BFS and DFS and when to use them.
A graph consists of nodes (vertices) and edges (connections between nodes). In a graph:
1. Undirected: The edges have no direction. (e.g., A-B means you can go from A to B and
from B to A.)
2. Directed: The edges have direction. (e.g., A → B means you can only go from
A to B, not the other way around.)
BFS is a graph traversal algorithm that explores the graph level by level, starting from a node
and visiting all its neighbors before moving on to the next level.
BFS Algorithm:
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges.
DFS explores as far as possible along each branch before backtracking. It can be implemented
recursively or iteratively using a stack.
Time Complexity: O(V + E) where V is the number of vertices and E is the number of edges.
Now, let's implement BFS for the graph using the adjacency matrix.
#include <stdio.h>
#include <stdbool.h>
#define MAX_QUEUE_SIZE 100
Int count = 0;
// Queue structure
struct Queue {
int items[MAX_QUEUE_SIZE];
int front;
int rear;
};
// Queue functions
void initQueue(struct Queue* q) {
q->front = 0;
q->rear = -1;
}
// BFS function
void bfs(int vertices, int startVertex) {
bool visited[vertices];
for (int i = 0; i < vertices; i++) {
visited[i] = false;
}
struct Queue q;
initQueue(&q);
visited[startVertex] = true;
enqueue(&q, startVertex);
#include <stdio.h>
#include <stdbool.h>
// DFS function
void dfs(int vertices, int vertex, bool visited[]) {
visited[vertex] = true;
printf("Visited %d\n", vertex);
Task: Implement a program that performs a BFS traversal starting from any node in a graph.
● Use the starter code and modify the main() function to create a graph, add edges, and
perform BFS.
● Print the visited nodes in BFS order.
-------------------------------------------------------------------------------------------------------------------------------
Task: Implement a program that performs a DFS traversal starting from any node in a graph.
● Use the starter code and modify the main() function to create a graph, add edges, and
perform DFS..
● Print the visited nodes in DFS order.
-------------------------------------------------------------------------------------------------------------------------------
Task: Given a graph, check if it is connected or not. A graph is connected if there is a path
between every pair of vertices. If all vertices can be reached starting from any arbitrary vertex
(e.g., vertex 0), the graph is connected; otherwise, it's disconnected.
#include <stdio.h>
#include <stdbool.h>
int main() {
int vertices = 6;
initGraph(vertices);
return 0;
}
Hints:
1. DFS or BFS: You will need to perform a DFS or BFS starting from an arbitrary vertex
(usually vertex 0).
○ Initialize a visited[] array to keep track of visited vertices.
○ Mark the starting vertex as visited, then visit all its neighbors, recursively or
iteratively (using a queue for BFS).
2. Checking Connectivity: After the traversal, check if all vertices were visited. If they
were, the graph is connected. Otherwise, it’s disconnected.
3. Edge Case: If there's only one vertex, the graph is trivially connected.
-------------------------------------------------------------------------------------------------------------------------------
Task: Given an undirected graph, detect if the graph contains a cycle. A cycle is a path where
you can start at a vertex, traverse edges, and return to the same vertex.
#include <stdio.h>
#include <stdbool.h>
return false;
}
int main() {
int vertices = 6;
initGraph(vertices);
return 0;
}
Hints:
-------------------------------------------------------------------------------------------------------------------------------
Task: Given an undirected graph, count the number of connected components. A connected
component is a set of vertices where there is a path between any two vertices in the set, and no
vertex in the set is connected to any vertex outside the set.
#include <stdio.h>
#include <stdbool.h>
int main() {
int vertices = 6;
initGraph(vertices);
return 0;
}
Hints:
1. DFS or BFS: You will need to use DFS (or BFS) to explore the graph.
○ From an unvisited vertex, perform DFS and mark all reachable vertices as
visited.
○ Every time you start a new DFS from an unvisited vertex, you’ve discovered a
new connected component.
2. Visited Array:
○ Keep track of visited vertices with a visited[] array.
○ Initially, all elements in the visited[] array should be false.
3. Counting Components:
○ Each time you find an unvisited vertex, perform DFS from that vertex, marking all
reachable vertices as visited.
○ Increment the component count each time a DFS starts from an unvisited vertex.
4. Multiple Components:
○ If the graph is disconnected, there will be multiple DFS calls, each discovering a
different connected component.
○ Ensure that you start DFS from each unvisited vertex to account for all connected
components in the graph.
5. Edge Case:
○ If there is only one vertex, the graph has only one connected component (the
vertex itself).
Homework Problems
1. Print All Connected Components.
2. Find All Nodes at a Given Distance from a Source Node (Using BFS) in a Directed
Graph.
3. Find if a Path Exists Between Two Nodes in a Directed Graph.
4. Find the Number of Isolated Nodes.
5. Count the Number of Leaf Nodes in a Directed Graph.
6. Find the Diameter of a Graph (Longest Path Between Two Nodes).
7. Check if a Graph is Bipartite.