BFS, DFS
BFS, DFS
Graph Traversal Algorithms: Depth-First Search (DFS) and Breadth-First Search (BFS)
Objective
The objective of this lab is to implement and understand the Depth-First Search (DFS) and
Breadth-First Search (BFS) algorithms. These traversal methods allow us to explore all nodes in
a graph, which is useful in various applications like finding paths, detecting cycles, and
determining connected components.
Theory
Graphs consist of nodes (vertices) connected by edges. The two primary graph traversal
techniques are:
Below is the C code implementing DFS and BFS for an undirected graph.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int vertex;
struct Node* next;
};
struct Graph {
int numVertices;
struct Node** adjLists;
int* visited;
};
struct Queue {
int items[MAX];
int front;
int rear;
};
return graph;
}
// DFS algorithm
void DFS(struct Graph* graph, int vertex) {
struct Node* adjList = graph->adjLists[vertex];
struct Node* temp = adjList;
graph->visited[vertex] = 1;
printf("%d ", vertex);
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
// BFS algorithm
void BFS(struct Graph* graph, int startVertex) {
struct Queue* queue = createQueue();
graph->visited[startVertex] = 1;
enqueue(queue, startVertex);
while (!isEmpty(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(queue, adjVertex);
}
temp = temp->next;
}
}
printf("\n");
}
int main() {
struct Graph* graph = createGraph(5);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
BFS(graph, 0);
return 0;
}