Dsa Ass 5
Dsa Ass 5
Roll no- 75
Problem Statement- Create a graph and implement DFS using adjacency matrix. assignment
1. Objective
To create a graph using an adjacency matrix representation and implement Depth-First Search (DFS)
for graph traversal.
2. Definition
Graph: A collection of vertices (nodes) connected by edges. It can be directed or undirected.
Adjacency Matrix: A 2D array used to represent a graph. If there's an edge between vertex
uuu and vvv, adj[u][v]=1adj[u][v] = 1adj[u][v]=1, otherwise adj[u][v]=0adj[u][v] = 0adj[u]
[v]=0.
Depth-First Search (DFS): A graph traversal technique where the algorithm starts at a node,
explores as far as possible along each branch, and backtracks when necessary.
3. Theory
1. Graph Representation:
o An adjacency matrix is a square matrix of size n×nn \times nn×n, where nnn is the
number of vertices.
o For undirected graphs, the matrix is symmetric.
2. Depth-First Search:
o DFS starts from a specified vertex and visits nodes as deep as possible before
backtracking.
o It is implemented using recursion or a stack.
5. Code
#include <iostream>
#include <vector>
using namespace std;
class Graph {
private:
int vertices; // Number of vertices
vector<vector<int>> adjMatrix; // Adjacency matrix
public:
// Constructor to initialize the graph
Graph(int v) {
vertices = v;
adjMatrix.resize(v, vector<int>(v, 0));
}
int main() {
// Create a graph with 5 vertices
Graph g(5);
// Add edges
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
return 0;
}
6. Output