-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathBFS.cpp
More file actions
107 lines (86 loc) · 1.16 KB
/
BFS.cpp
File metadata and controls
107 lines (86 loc) · 1.16 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
void enqueue(int x)
{
struct Node* t = (struct Node*)malloc(sizeof(struct Node));
if(t==NULL)
printf("memory problem");
else
{
t->data = x;
t->next = NULL;
if(front == NULL) //empty
{
front = rear = t;
}
else
{
rear->next = t;
rear = t;
}
}
}
int dequeue()
{
int x;
struct Node* t;
if(front == NULL)
{
printf("queue is empty");
return -1;
}
else
{
t = front;
x = t->data;
front = front->next;
free(t);
}
return x;
}
int isEmpty()
{
return front == NULL;
}
void BFS(int G[][7], int start, int n)
{
int i = start;
int visited[n] = {0};
printf("%d ",i);
enqueue(i);
visited[i] = 1;
while(!isEmpty())
{
i = dequeue();
for(int j = 0; j<n; j++)
{
if(G[i][j] == 1 && visited[j] == 0)
{
printf("%d ",j);
enqueue(j);
visited[j] = 1;
}
}
}
}
int main()
{
int G[7][7] = {
{0,1,1,1,0,0,0},
{1,0,0,1,0,0,0},
{1,0,0,1,1,0,0},
{1,1,1,0,1,0,0},
{0,0,1,1,0,1,1},
{0,0,0,0,1,0,0},
{0,0,0,0,1,0,0}
};
BFS(G,3,7);
return 0;
}