0% found this document useful (0 votes)
4 views8 pages

BFS and DFS Lab Report for CSE 206

Uploaded by

asifaib.bm
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)
4 views8 pages

BFS and DFS Lab Report for CSE 206

Uploaded by

asifaib.bm
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

Green University of Bangladesh

Department of Computer Science and Engineering (CSE)


Faculty of Sciences and Engineering
Semester: (Spring, Year:2024), [Link]. in CSE (Day)

Lab Report NO # 01
Course Title: Algorithms Lab
Course Code: CSE 206 Section: 223,D4

Lab Experiment Name: Write program to


BFS Cycle Detection and Path Finding & DFS for Topological Sort
Student Details

Name ID

1. Moinul Hasan 221902281

Lab Date : 19/09/2024


Submission Date : 26/09/2024
Course Teacher’s Name : Md. Abu Rumman Refat

Lab Report Status


Marks: ………………………………… Signature:.....................
Comments:.............................................. Date:..............................
1. TITLE OF THE LAB REPORT EXPERIMENT
Write program to BFS Cycle Detection and Path Finding , DFS for Topological
Sort

2. OBJECTIVES

1. Breadth-First Search (BFS) :


- Detect cycles in an undirected graph using BFS.
- Find the shortest path between two nodes in an undirected graph.

2. Depth-First Search (DFS) :


- Perform a topological sort on a Directed Acyclic Graph (DAG) using DFS.

Through this lab, the aim is to gain a practical understanding of BFS and DFS
traversal techniques, cycle detection mechanisms, shortest path finding, and the
importance of topological sorting in organizing dependencies in a directed graph.
This also helps in comparing the applicability of BFS and DFS for different graph-
based problems.

3. PROCEDURE
1. Define graph structure using adjacency lists.
2. Implement BFS for cycle detection.
3. Implement BFS for shortest path finding.
4. Implement DFS for topological sorting.
5. Test BFS for cycle detection and pathfinding.
6. Test DFS for topological sort.
7. Analyze and verify results.

4. IMPLEMENTATION

Source code:
1. BFS Cycle Detection and Path Finding:
import [Link].*;

class GraphBFS {
private int V;
private LinkedList<Integer>[] adjList;

GraphBFS(int v) {
V = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new LinkedList<>();
}
}
void addEdge(int v, int w) {
adjList[v].add(w);
adjList[w].add(v);
}
boolean detectCycle() {
boolean[] visited = new boolean[V];
int[] parent = new int[V];
for (int i = 0; i < V; i++) {
if (!visited[i]) {
if (bfsCycleCheck(i, visited, parent)) {
return true;
}
}
}
return false;
}
private boolean bfsCycleCheck(int src, boolean[] visited, int[] parent) {
Queue<Integer> queue = new LinkedList<>();
[Link](src);
visited[src] = true;
while (![Link]()) {
int node = [Link]();
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
[Link](neighbor);
parent[neighbor] = node;
} else if (parent[node] != neighbor) {
return true;
}
}
}
return false;
}

List<Integer> bfsShortestPath(int src, int dest) {


boolean[] visited = new boolean[V];
int[] parent = new int[V];
[Link](parent, -1);

Queue<Integer> queue = new LinkedList<>();


[Link](src);
visited[src] = true;

while (![Link]()) {
int node = [Link]();

if (node == dest) {
break; }

for (int neighbor : adjList[node]) {


if (!visited[neighbor]) {
visited[neighbor] = true;
parent[neighbor] = node;
[Link](neighbor);
}
}
}
List<Integer> path = new ArrayList<>();
for (int at = dest; at != -1; at = parent[at]) {
[Link](at);
}

[Link](path);
if ([Link](0) == src) {
return path;
} else {
return [Link]();
}
}

public static void main(String[] args) {


GraphBFS graph = new GraphBFS(6);
[Link](0, 1);
[Link](0, 2);
[Link](1, 3);
[Link](3, 4);
[Link](4, 5);

[Link]("Cycle detected: " + [Link]());

int source = 0, destination = 5;


List<Integer> path = [Link](source, destination);
if (![Link]()) {
[Link]("Shortest path from " + source + " to " + destination + ": " + path);
} else {
[Link]("No path exists between " + source + " and " + destination);
}
}
}
Output:

2. DFS for Topological Sort:

import [Link].*;

class GraphDFS {
private int V;
private LinkedList<Integer>[] adjList; // Adjacency list
GraphDFS(int v) {
V = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++) {
adjList[i] = new LinkedList<>();
}
}
void addEdge(int v, int w) {
adjList[v].add(w); }
private void dfsTopologicalSort(int node, boolean[] visited, Stack<Integer> stack) {
visited[node] = true;

for (int neighbor : adjList[node]) {


if (!visited[neighbor]) {
dfsTopologicalSort(neighbor, visited, stack);
}
}

[Link](node);
}

// Perform topological sort


void topologicalSort() {
boolean[] visited = new boolean[V];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < V; i++) {
if (!visited[i]) {
dfsTopologicalSort(i, visited, stack);
}
}

[Link]("Topological sort order:");


while (![Link]()) {
[Link]([Link]() + " ");
}
[Link]();
}

public static void main(String[] args) {


GraphDFS graph = new GraphDFS(6);
[Link](5, 2);
[Link](5, 0);
[Link](4, 0);
[Link](4, 1);
[Link](2, 3);
[Link](3, 1);

[Link]();
}
}

Output:
ANALYSIS AND DISCUSSION

In this lab, BFS and DFS were applied to solve different graph problems. BFS was used for cycle
detection and shortest path finding in an undirected graph. It efficiently detects cycles by checking
re-visited nodes and guarantees the shortest path in unweighted graphs, with time complexity O(V
+ E). Meanwhile, DFS was utilized for topological sorting in a Directed Acyclic Graph (DAG), correctly
producing a valid ordering of nodes based on dependencies. While BFS is best for shortest paths, DFS excels
in organizing tasks with dependencies. Both algorithms are crucial in different graph-related applications,
demonstrating

Common questions

Powered by AI

Cycle detection is critical in scenarios such as detecting deadlocks in concurrent systems or identifying redundant network paths that could lead to infinite loops. In the lab example, implementing BFS for cycle detection revealed the need to identify paths to avoid, ensuring effective graph navigation and data processing without encountering repeated paths or stalled executions .

Test cases illustrating limitations of BFS may include graphs where shortest paths or cycles are not relevant, such as in scenarios requiring ordering, where DFS excels. Conversely, cases challenging DFS might involve finding the actual shortest path in an unweighted graph, where DFS would not necessarily lead to optimal solutions due to its depth-first nature. The lab's focus on distinct applications like shortest path and topological sort underlines each algorithm's strengths and limits when applied to different graph structures or problem requirements .

While BFS is effective for finding shortest paths in unweighted graphs due to its level-by-level exploration, it is not suitable for weighted graphs where edge weights influence the total path cost. In weighted graph scenarios, algorithms like Dijkstra's are preferable as they account for edge weights while determining the shortest path. The lab helps underline this limitation of BFS, showcasing its optimal use is restricted to contexts where path length is measured in discrete steps without varied edge costs .

DFS is more beneficial than BFS when dealing with problems that require exploration of paths to their deepest limits first, such as topological sorting in a Directed Acyclic Graph (DAG). DFS is ideal for scenarios where task ordering or dependency resolution is needed, as it efficiently handles backtracking. In contrast, BFS is better suited for finding shortest paths in unweighted graphs .

Topological sorting is crucial for tasks that require dependency ordering, such as scheduling in project management or resolving build orders in software engineering. The lab's implementation of DFS for topological sorting in a Directed Acyclic Graph (DAG) demonstrates its significance by providing a valid node ordering based on dependencies, ensuring that each node is processed only after all its requisite predecessors. This capacity for ordered task execution underscores DFS's role in efficiently organizing complex conditional sequences .

Adjacency lists are advantageous because they are space-efficient, especially for sparse graphs where few edges exist relative to the number of nodes. This efficiency allows easy iteration over neighbors of a given node, which is beneficial for BFS and DFS operations used in the lab. Adjacency matrices, conversely, use more space as they require storage for all possible edges, increasing complexity in modification and traversal tasks .

BFS finds the shortest path in an unweighted graph by exploring all neighbors of a node before moving to the next level nodes. By tracking visited nodes and maintaining a queue, BFS ensures the shortest path since it visits nodes layer by layer. In the lab, BFS was demonstrated by finding the shortest path from node 0 to node 5, resulting in the path [0, 2, 3, 1, 4, 5] being identified and printed as the shortest .

DFS achieves topological sorting in a DAG by recursively visiting each node's neighbors before marking the node as completed. It utilizes a stack to record the order of completion, providing a reverse finish order as the topological sort. From the lab example, with edges such as (5,2), (5,0), and (4,1), the output order was 5 4 2 0 3 1, indicating a valid sequence respecting all dependent tasks .

BFS detects cycles in an undirected graph by keeping track of parent nodes. As it traverses the graph, it visits unvisited nodes and marks them, along with maintaining a parent reference for each node. If it comes across a previously visited node that isn't a parent of the current node, a cycle is detected .

Both BFS and DFS have a time complexity of O(V + E) where V is the number of vertices and E is the number of edges. However, the space requirements differ: BFS requires additional space for maintaining the queue, potentially leading to higher memory usage in dense graphs. DFS, meanwhile, can be implemented with stack data, making it generally more space-efficient than BFS. The lab emphasized these differences, showcasing BFS's additional usefulness for cycle detection and shortest paths due to thorough level-order exploration .

You might also like