AI LAB Experiment 1
AI LAB Experiment 1
AI LAB Experiment 1
Aim: Implement Breadth first and depth first search techniques.
Theory:
Breadth-First Search (BFS) and Depth-First Search (DFS) are graph traversal
algorithms used
to explore nodes in a graph or tree. BFS:
Strategy: Explores nodes level by level, using a queue.
Key Feature: Finds the shortest path in an unweighted graph.
Applications: Shortest path in unweighted graphs, level-order traversal in trees.
DFS:
Strategy: Explores as deep as possible along a branch before backtracking, using
a stack (or
recursion).
Key Feature: May not find the shortest path but explores all paths deeply.
Applications: Pathfinding, solving puzzles, topological sorting.
Code:
DFS:
#include <iostream>
Node(int val) {
value = val;
left = right = nullptr;
}
};
// Driver code
int main() {
// Creating the binary tree
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
OutPut
2|Page
Name: Ashutosh Kumar Reg. Num: 231070006 Batch: A
BFS:
#include <iostream>
#include <queue>
Node(int val) {
value = val;
left = right = nullptr;
}
};
queue<Node*> q;
q.push(root); // Enqueue root
while (!q.empty()) {
Node* node = q.front(); // Dequeue
q.pop();
cout << node->value << " "; // Process the current node
// Driver code
int main() {
// Creating the binary tree
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
3|Page
Name: Ashutosh Kumar Reg. Num: 231070006 Batch: A
return 0;
}
Output:
Conclusion :
BFS (Breadth-First Search) explores the graph level by level, making it ideal for
finding the shortest path in
unweighted graphs. It uses a queue and is more memory-intensive for wide
graphs.
DFS (Depth-First Search) explores the graph by going
deep into one branch before backtracking, making it suitable
4|Page
Name: Ashutosh Kumar Reg. Num: 231070006 Batch: A
5|Page