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

Port City International University: Submitted To

algorithm conectivity
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)
9 views4 pages

Port City International University: Submitted To

algorithm conectivity
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

PORT CITY INTERNATIONAL UNIVERSITY

COURSE CODE: CSE 228

COURSE TITLE: Algorithm Sessional

NAME OF THE LAB REPORT: DFS connectivity

Date of submission: 19.09.2024

SUBMITTED TO

Name of the Lecturer: Tanvinur Rahman Siam(Lecturer)

Department: Computer Science and Engineering

SUBMITTED BY

Name: Mohammed Thohidul Alam Chy.

Program: BSc in CSE

ID no: CSE 030 07814

Batch no: 30-D-A1


Implementation:
Source Code:
#include <iostream>
using namespace std;

#define MAX_NODES 100

int adj[MAX_NODES][MAX_NODES];
int visited[MAX_NODES];

void dfs(int node, int n) {


visited[node] = 1;
for (int i = 0; i < n; i++) {
if (adj[node][i] && !visited[i]) {
dfs(i, n);
}
}
}

int main() {
int n, edges, u, v, start, target;

cout << "Enter number of nodes: ";


cin >> n;
cout << "Enter number of edges: ";
cin >> edges;

for (int i = 0; i < n; i++) {


for (int j = 0; j < n; j++) {
adj[i][j] = 0;
}
}

for (int i = 0; i < edges; i++) {


cout << "Enter edge (u,v): ";
cin >> u >> v;
adj[u][v] = 1;
adj[v][u] = 1;
}

cout << "Enter start node and target node: ";


cin >> start >> target;

for (int i = 0; i < n; i++) {


visited[i] = 0;
}

dfs(start, n);

if (visited[target]) {
cout << "Nodes " << start << " and " << target << " are connected" << endl;
} else {
cout << "Nodes " << start << " and " << target << " are not connected" <<
endl;
}

return 0;
}
Output:

Discussion:
Here we are using dfs to check if any two nodes are connected in a graph.
Dfs(depth first search) works in a way that goes to the maximum depth meaning it
will run until a node with no children is found. While visiting the nodes they will
keep track of the visited nodes. When we check the connectivity we start dfs from
the node that is the source and then check either the destination node is visited the
from the source node if it’s visited we can say they are connected if not they are
not connected.

You might also like