0% found this document useful (0 votes)
4 views

Emon Algorithm Report01

Uploaded by

asifaib.bm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Emon Algorithm Report01

Uploaded by

asifaib.bm
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Green University of Bangladesh

Department of Computer Science and Engineering


(CSE)
Faculty of Sciences and Engineering
Semester: (Spring, Year:2024), B.Sc. 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 java.util.*;

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<>();
queue.add(src);
visited[src] = true;
while (!queue.isEmpty()) {
int node = queue.poll();
for (int neighbor : adjList[node])
{ if (!visited[neighbor])
{
visited[neighbor] = true;
queue.add(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];
Arrays.fill(parent, -1);

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


queue.add(src);
visited[src] = true;

while (!queue.isEmpty()) {
int node = queue.poll();

if (node == dest)
{ break; }

for (int neighbor : adjList[node])


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

Collections.reverse(path);
if (path.get(0) == src) {
return path;
} else {
return Collections.emptyList();
}
}

public static void main(String[] args) {


GraphBFS graph = new
GraphBFS(6); graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 5);

System.out.println("Cycle detected: " +

graph.detectCycle()); int source = 0, destination = 5;


List<Integer> path = graph.bfsShortestPath(source,
destination); if (!path.isEmpty()) {
System.out.println("Shortest path from " + source + " to " + destination + ": " + path);
} else {
System.out.println("No path exists between " + source + " and " + destination);
}
}
}
Output:

2. DFS for Topological Sort:

import java.util.*;

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);
}
}

stack.push(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);
}
}

System.out.println("Topological sort order:");


while (!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
System.out.println();
}

public static void main(String[] args)


{ GraphDFS graph = new
GraphDFS(6); graph.addEdge(5, 2);
graph.addEdge(5, 0);
graph.addEdge(4, 0);
graph.addEdge(4, 1);
graph.addEdge(2, 3);
graph.addEdge(3, 1);

graph.topologicalSort();
}
}

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

You might also like