-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.c
89 lines (73 loc) · 1.74 KB
/
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
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <string.h>
#define max 10000
int n, size = 0, size2 = 0;
char color [100][10];
int q[100], prev[100], val[100];
void bfs(int graph[][n], int s){
for(int i=0; i<n; i++){
strcpy(color[i], "White");
prev[i] = max;
}
strcpy(color[s], "Grey");
q[size] = s;
size++;
while(size!=0){
int a = q[0];
for(int i=1; i<size; i++){
q[i-1] = q[i];
}
size--;
for(int i=0; i<n; i++){
if((graph[a][i] == 1) && (!strcmp(color[i], "White"))){
strcpy(color[i], "Grey");
prev[i] = a;
q[size] = i;
size++;
}
}
strcpy(color[a], "Black");
val[size2] = a;
size2++;
}
printf("Printing bfs array - ");
for(int p=0; p<n; p++){
printf("%d ", val[p]);
}
}
// //path printing code
void printPath(int prev[], int a, int b){
if(a==b){
printf("%d\t", a);
}
else if(prev[b]==max){
printf("");
}
else {
printPath(prev, a, prev[b]);
printf("%d\t", b);
}
}
int main(void){
printf("Enter number of node - ");
scanf("%d", &n);
int arr[n][n];
//creating graph
printf("Enter Graph [in matrix form] - \n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
scanf("%d", &arr[i][j]);
}
}
//printing graph
printf("Graph is [in matrix form] - \n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
//bfs run
bfs(arr, 0);
return 0;
}