-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.c
More file actions
101 lines (88 loc) · 1.41 KB
/
bfs.c
File metadata and controls
101 lines (88 loc) · 1.41 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
// Consider a Graph G Perform Breadth First Traversal on the given graph. Vertices of the graph goes like 1, 2, 3 ...... n.
// Input :
// n - Integer - number of vertices
// nxn - adjacency matrix for the graph G
// m - Integer - starting vertex
// Output:
// List of n vertices - BFS Order.
// For example:
// Input Result
// 4
// 0 1 0 1
// 1 0 1 0
// 0 1 0 0
// 1 0 0 0
// 2
// 2
// 1
// 3
// 4
#include <stdio.h>
#define max 100
int queue[max];
int f = -1, r = -1;
int isEmpty()
{
if (f == -1)
{
return 1;
}
else
{
return 0;
}
}
void enqueue(int x)
{
r++;
queue[r] = x;
if (f == -1)
{
f++;
}
}
int dequeue()
{
int temp = queue[f];
if (f == r)
{
f = r = -1;
}
else
{
f++;
}
return temp;
}
int main()
{
int n, start;
scanf("%d", &n);
int adjmat[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &adjmat[i][j]);
}
}
scanf("%d", &start);
int visited[n];
--start;
visited[start] = 1;
enqueue(start);
while (!isEmpty())
{
int x = dequeue();
printf("%d\n", x + 1);
for (int i = 0; i < n; i++)
{
if (adjmat[x][i] == 1 && visited[i] != 1)
{
enqueue(i);
visited[i] = 1;
}
}
}
return 0;
}