forked from sudhanshu-p/dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp9.c
78 lines (73 loc) · 2.08 KB
/
p9.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
#include<stdio.h>
#include<stdlib.h>
void dfs (int n, int graph[][n], int visited[], int s);
void bfs (int n, int graph[][n], int visit[], int x);
int main() {
int n;
printf("Enter the number of nodes in the graph: ");
scanf("%d", &n);
int arr [n][n];
int visited [n];
printf("Enter the Adjacency Matrix: \n");
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
scanf("%d", &arr[i][j]);
int c, l=1, val;
while(1) {
printf("\n----------------\nNow select the search you want to perform: \n1: Depth First Search\n2: Breadth First Search\n-1: Exit\nYour Choice: ");
scanf("%d", &c);
if(c == -1)
break;
for(int i=0; i<n; i++)
visited[i]=0;
switch(c) {
case 1:
printf("Enter a source node for DFS\n");
scanf("%d",&val);
printf("DFS:\n ");
dfs(n, arr, visited, val);
printf("\n");
break;
case 2:
printf("Enter a source node for BFS\n");
scanf("%d",&val);
printf("BFS:\n");
bfs(n, arr, visited, val);
break;
default:
printf("Enter a valid choice\n");
}
}
printf("Goodbye!");
}
void dfs(int n, int graph[][n], int visited[], int s) {
int j=0;
visited[s]=1;
printf("%d , ",s);
for(int j=0; j<n ; j++)
if(graph[s][j]==1 && visited[j]==0)
dfs(n,graph,visited,j);
}
void bfs(int n, int graph[][n], int visit[], int x) {
printf("%d, ",x);
int q[n], f = -1, r = -1, visit_count = 0;
visit[x]=1;
f = f + 1;
r = r + 1;
q[r]=x;
while(f<=r) {
x=q[f];
f=f+1;
visit_count=0;
while(visit_count<n) {
if(graph[x][visit_count]==1 && visit[visit_count]==0) {
visit[visit_count]=1;
r=r+1;
q[r]=visit_count;
printf("%d, ",visit_count);
}
visit_count=visit_count+1;
}
}
printf("\n");
}