-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS_BFS.c
81 lines (70 loc) · 1.91 KB
/
DFS_BFS.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int adj_matrix[MAX_SIZE][MAX_SIZE], visited[MAX_SIZE];
int queue[MAX_SIZE], front = -1, rear = -1, top = -1, stack[MAX_SIZE];
void dfs(int v, int n) {
visited[v] = 1;
printf("%d ", v);
for(int i=0; i<n; i++) {
if(adj_matrix[v][i] && !visited[i]) {
dfs(i, n);
}
}
}
void bfs(int v, int n) {
visited[v] = 1;
queue[++rear] = v;
while(front != rear) {
int u = queue[++front];
printf("%d ", u);
for(int i=0; i<n; i++) {
if(adj_matrix[u][i] && !visited[i]) {
visited[i] = 1;
queue[++rear] = i;
}
}
}
}
int main() {
int choice, n, source;
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
scanf("%d", &adj_matrix[i][j]);
}
}
printf("Enter the source vertex: ");
scanf("%d", &source);
while(1) {
printf("\n1. DFS\n2. BFS\n3. Quit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("DFS traversal: ");
for(int i=0; i<n; i++) {
visited[i] = 0;
}
dfs(source, n);
printf("\n");
break;
case 2:
printf("BFS traversal: ");
for(int i=0; i<n; i++) {
visited[i] = 0;
}
front = rear = -1;
bfs(source, n);
printf("\n");
break;
case 3:
exit(0);
default:
printf("Invalid choice\n");
}
}
return 0;
}