0% found this document useful (0 votes)
28 views4 pages

Ai Exp2 - 2

The document outlines the implementation and theory behind two uninformed search algorithms: Breadth-First Search (BFS) and Depth-First Search (DFS). BFS explores nodes level by level using a queue, ensuring the shortest path in unweighted graphs, while DFS explores as far as possible along each branch using a stack, making it suitable for exhaustive searches. Both algorithms are implemented in Java, demonstrating their functionality through a sample tree structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views4 pages

Ai Exp2 - 2

The document outlines the implementation and theory behind two uninformed search algorithms: Breadth-First Search (BFS) and Depth-First Search (DFS). BFS explores nodes level by level using a queue, ensuring the shortest path in unweighted graphs, while DFS explores as far as possible along each branch using a stack, making it suitable for exhaustive searches. Both algorithms are implemented in Java, demonstrating their functionality through a sample tree structure.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

EXPERIMENT 2

AIM : WAP on Uninformed search methods BFS and DFS FAlgorithms (c/c++/Java/Python
Prolog)

THEORY :

BFS (Breadth-First Search) Algorithm:


Theory:
• BFS is an algorithm used for traversing or searching graph or tree data structures.
• It explores all the nodes at the present depth level before moving on to the nodes at the next
depth level.
• BFS works by visiting the starting node, then exploring all its neighbors (nodes at distance
1), then visiting all their neighbors (nodes at distance 2), and so on until all reachable nodes
are visited.
Key Features:
• Queue-based: BFS uses a queue (FIFO structure) to keep track of nodes to visit.
• Layered exploration: BFS explores nodes level by level. All nodes at distance n are
explored before any node at distance n+1.
• Optimal for finding the shortest path in an unweighted graph: BFS guarantees finding the
shortest path from the source node to any other node in an unweighted graph.
Steps:
1. Start with the source node, mark it as visited, and enqueue it in a queue.
2. While the queue is not empty:
• Dequeue a node from the queue.
• For each unvisited neighbor of this node, mark it as visited and enqueue it.
3. Repeat until all nodes are visited.
Time Complexity:
• O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Use Cases:
• Finding the shortest path in an unweighted graph.
• Solving puzzles like the "8-puzzle" or "solving mazes."
• Web crawling (traverse all websites in a given domain).

DFS (Depth-First Search) Algorithm:


Theory:
• DFS is an algorithm used for traversing or searching graph or tree data structures.
• It starts at the root (or an arbitrary node in the case of a graph) and explores as far as
possible along each branch before backtracking.
• DFS explores deeper into the graph or tree by visiting one node and its descendants before
returning to the parent node to explore other children.
Key Features:
• Stack-based: DFS uses a stack (either explicitly or via recursion) to keep track of the nodes
to visit.
• Depth-oriented exploration: DFS goes deep into the graph by following one path as far as
it can before backtracking and trying another path.
• Not guaranteed to find the shortest path in unweighted graphs, unlike BFS.
Steps:
1. Start from the source node, mark it as visited.
2. For each unvisited neighbor of the current node, recursively visit the neighbor.
3. Repeat the process until all nodes are visited.
Time Complexity:
• O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Use Cases:
• Pathfinding where the goal is not necessarily the shortest path but rather to explore or reach
any node.
• Topological sorting in directed acyclic graphs (DAGs).
• Solving problems like mazes, puzzles, and cycles detection in graphs.

Conclusion: BFS and DFS Algorithms


Both Breadth-First Search (BFS) and Depth-First Search (DFS) are fundamental algorithms for
traversing or searching through graphs and trees. Each has its unique characteristics, strengths, and
applications:
1. BFS:
• BFS is ideal when the goal is to explore nodes level by level, making it particularly
effective for problems that require finding the shortest path in an unweighted graph.
• It guarantees the shortest path to the destination if all edges have equal weight.
• Its use of a queue ensures that nodes are processed in the order they are discovered,
and the algorithm is memory-intensive in cases of large graphs due to its need to
store all nodes at the current level.
• Applications: Shortest path algorithms, web crawling, social network analysis, and
solving puzzles like mazes.
2. DFS:
• DFS is well-suited for exploring deep into a graph or tree, making it effective in
problems where exhaustive searching is required, such as searching for paths,
detecting cycles, and performing topological sorting.
• While it does not guarantee the shortest path, it is efficient in terms of space, as it
uses either an explicit stack or recursion.
Program:
import java.util.*;

class Tree {
private Map<Integer, List<Integer>> adjList = new HashMap<>();
private int nodesVisited = 0;

public void addEdge(int parent, int child) {


adjList.computeIfAbsent(parent, k -> new ArrayList<>()).add(child);
}

public void BFS(int root) {


Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.add(root);
visited.add(root);
nodesVisited = 0;

System.out.println("\nAlgorithm used = BFS");


while (!queue.isEmpty()) {
int node = queue.poll();
nodesVisited++;
for (int child : adjList.getOrDefault(node, Collections.emptyList())) {
if (!visited.contains(child)) {
queue.add(child);
visited.add(child);
}
}
}
System.out.println("Path found!!");
System.out.println("Total nodes visited = " + nodesVisited);
System.out.println("Shortest path steps = " + (nodesVisited - 1));
}

public void DFS(int root) {


Set<Integer> visited = new HashSet<>();
nodesVisited = 0;

System.out.println("\nAlgorithm used = DFS");


DFSUtil(root, visited);
System.out.println("Path found!!");
System.out.println("Total nodes visited = " + nodesVisited);
System.out.println("Steps with backtracking = " + (nodesVisited - 1));
}

private void DFSUtil(int node, Set<Integer> visited) {


if (!visited.add(node)) return;
nodesVisited++;
for (int child : adjList.getOrDefault(node, Collections.emptyList())) {
DFSUtil(child, visited);
}
}

public static void main(String[] args) {


Tree tree = new Tree();
tree.addEdge(1, 2);
tree.addEdge(1, 3);
tree.addEdge(2, 4);
tree.addEdge(2, 5);
tree.addEdge(3, 6);
tree.addEdge(3, 7);

System.out.println("main start");
tree.BFS(1);
tree.DFS(1);
}
}

OUTPUT:

You might also like