Content Beyond Syllabus
Content Beyond Syllabus
AIM:
ALGORITHM:
THEORY:
Breadth-First Search (BFS) is an algorithm used for traversing or searching tree or graph
data structures. It starts at a selected node (known as the "start vertex") and explores all
its neighboring nodes at the present depth before moving on to nodes at the next depth
level. BFS is particularly useful for finding the shortest path in an unweighted graph.
Key Concepts:
Steps in BFS:
1. Initialization:
o Start by marking the start vertex as visited and enqueue it.
2. Processing:
o Dequeue a vertex and process it (typically involves printing or performing
some operations).
o For each adjacent vertex of the dequeued vertex, if it has not been visited,
mark it as visited and enqueue it.
3. Termination:
o Continue this process until the queue is empty, meaning all reachable
vertices from the start vertex have been visited.
Advantages of BFS:
Shortest Path: In an unweighted graph, BFS finds the shortest path from the
start vertex to any other vertex.
Complete and Optimal: BFS is complete (finds a solution if one exists) and
optimal (finds the shortest path) in unweighted graphs.
PROGRAM
#include <stdio.h>
#include <stdlib.h>
int dequeue() {
int vertex;
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
return -1;
} else {
vertex = queue[front++];
if (front > rear)
front = rear = -1;
return vertex;
}
}
void bfs(int startVertex) {
int i;
enqueue(startVertex);
visited[startVertex] = 1;
int main() {
int i, j, startVertex;
AIM:
ALGORITHM:
THEORY:
Depth-First Search (DFS) is an algorithm used for traversing or searching tree or graph
data structures. It starts at a selected node (known as the "start vertex") and explores as
far as possible along each branch before backtracking. DFS uses a stack-based approach
for traversal.
Key Concepts:
Steps in DFS:
1. Initialization:
o Start by marking the start vertex as visited and push it onto the stack.
2. Processing:
o Peek at the top vertex of the stack.
o For each adjacent vertex of the top vertex, if it has not been visited, push it
onto the stack, mark it as visited, and print it.
3. Backtracking:
o If no adjacent unvisited vertex is found, pop the stack to backtrack and
continue the search.
Advantages of DFS:
PROGRAM
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int stack[MAX], top = -1;
int adj[MAX][MAX], visited[MAX];
int n; // Number of vertices in the graph
void push(int vertex) {
if (top == MAX - 1)
printf("Stack Overflow\n");
else
stack[++top] = vertex;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
if (!found)
pop();
}
}
int main() {
int i, j, startVertex;