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

Ds 8

Uploaded by

ebinarul177
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)
15 views

Ds 8

Uploaded by

ebinarul177
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/ 2

#include <stdio.

h>

#define MAX 20

int adj_mat[MAX][MAX], visited[MAX];


int n;

void read_graph() {
char reply;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) {
adj_mat[i][j] = 0;
} else {
printf("Vertices %d & %d are adjacent? (Y/N): ", i, j);
getchar(); // Consume newline character from previous input
scanf("%c", &reply);
adj_mat[i][j] = (reply == 'Y' || reply == 'y') ? 1 : 0;
}
}
}
}

void print_graph() {
printf("\nAdjacency Matrix:\n");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
printf("%d ", adj_mat[i][j]);
}
printf("\n");
}
}

void bfs(int start) {


int queue[MAX], front = 0, rear = 0;
for (int i = 1; i <= n; i++) visited[i] = 0;

visited[start] = 1;
queue[rear++] = start;

printf("BFS: ");
while (front < rear) {
int v = queue[front++];
printf("%d ", v);

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


if (adj_mat[v][i] && !visited[i]) {
visited[i] = 1;
queue[rear++] = i;
}
}
}
printf("\n");
}

void dfs(int v) {
printf("%d ", v);
visited[v] = 1;

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


if (adj_mat[v][i] && !visited[i]) {
dfs(i);
}
}
}

int main() {
printf("Enter the number of vertices: ");
scanf("%d", &n);

read_graph();
print_graph();

int start;
printf("Enter the starting vertex for BFS: ");
scanf("%d", &start);
bfs(start);

printf("Enter the starting vertex for DFS: ");


scanf("%d", &start);
for (int i = 1; i <= n; i++) visited[i] = 0; // Reset visited array for DFS
printf("DFS: ");
dfs(start);
printf("\n");

return 0;
}

You might also like