DK 10
DK 10
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Data Structures
Course Name:_________________________ BH.USCSP304
Course Number: __________
Practical Number: _______ Page Number: _______
Aim:
AIM:
Implement BFS and DFS in a graph.
CODE:
#include <iostream>
using namespace std;
class Graph {
private:
int** adjMatrix;
int vertices;
public:
Graph(int V) {
vertices = V;
adjMatrix = new int*[vertices];
for (int i = 0; i < vertices; i++) {
adjMatrix[i] = new int[vertices];
for (int j = 0; j < vertices; j++) {
adjMatrix[i][j] = 0;
}
}
}
visited[start] = true;
Page 1 of 3
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Data Structures
Course Name:_________________________ BH.USCSP304
Course Number: __________
Practical Number: _______ Page Number: _______
Aim:
cout << "BFS starting from vertex " << start << ": ";
cout << start << " ";
int queue[vertices];
int front = 0, rear = 0;
queue[rear++] = start;
delete[] visited;
cout << endl;
}
cout << "DFS starting from vertex " << start << ": ";
dfsUtil(start, visited);
cout << endl;
delete[] visited;
}
~Graph() {
for (int i = 0; i < vertices; i++) {
delete[] adjMatrix[i];
}
delete[] adjMatrix;
}
};
int main() {
int V, E;
cout << "Enter the number of vertices: ";
Page 2 of 3
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Data Structures
Course Name:_________________________ BH.USCSP304
Course Number: __________
Practical Number: _______ Page Number: _______
Aim:
cin >> V;
cout << "Enter the number of edges: ";
cin >> E;
Graph g(V);
cout << "Enter " << E << " edges in the format (start end):" << endl;
for (int i = 0; i < E; i++) {
int start, end;
cin >> start >> end;
g.addEdge(start, end);
}
int startVertex;
cout << "Enter the starting vertex for BFS and DFS: ";
cin >> startVertex;
g.bfs(startVertex);
g.dfs(startVertex);
return 0;
}
OUTPUT:
Page 3 of 3