-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfsAdjacencyMatrix.c
92 lines (68 loc) · 1.5 KB
/
bfsAdjacencyMatrix.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
90
91
92
#include "adjMatrix.h"
#define max 100
#define unvisited 0
#define visited 1
#define processed 2
#define NIL -1
int queue[max], front, rear;
void initialiseQueue(){
front=-1;
rear=-1;
}
void enqueue(int ver){
if(rear==(max-1)) return;
if(queueIsEmpty()) // first time
front=0;
queue[++rear] = ver;
}
int queueIsEmpty(){
if( front==-1 && rear==-1 ) return 1;
else return 0;
}
int dequeue(){
if( !queueIsEmpty()){
int value = queue[front++];
if(front > rear) initialiseQueue();
return value;
}
else return -1; // means queue is empty
}
void bfs(int *adjMat, int v){
int i, j, u, source;
int *parent = (int*)malloc(v*sizeof(int));
int *status = (int*)malloc(v*sizeof(int));
for(i=0; i<v; i++){
parent[i] = NIL;
status[i]= unvisited;
}
printf("Enter source vertex: ");
scanf("%d", &source);
initialiseQueue();
enqueue(source);
status[source] = visited;
printf("BFS Traversal: ");
while(!queueIsEmpty()){
u = dequeue();
for(i=0; i<v; i++){
if( *(adjMat+(u*v)+i) >0 && status[i]==unvisited){
parent[i] = u;
status[i] = visited;
enqueue(i);
}
}
status[u] = processed;
printf("%d, ", u);
}
printf("\n\nParent Child\n");
for(i=0; i<v; i++){
printf(" %d\t %d\n", parent[i], i);
}
}
int main(){
int v, type;
int *adjMat = initializeGraph(&v);
type = inputGraph(adjMat, v);
displayGraph(adjMat, v);
bfs(adjMat, v);
return 0;
}