-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.c
More file actions
63 lines (49 loc) · 1.05 KB
/
bfs.c
File metadata and controls
63 lines (49 loc) · 1.05 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
#include <stdio.h>
#include<stdbool.h>
#define MAX 100
int q[MAX];
int front = 0;
int rear = 0;
int adj[MAX][MAX];
bool visited[MAX];
void push(int data){
q[rear++] = data;
}
int pop(){
return q[front++];
}
bool isEmpty(){
return front == rear;
}
void bfs(int nodes,int start){
push(start);
while(!isEmpty()){
int u = pop();
if(!visited[u]){
visited[u] = true;
printf("%d ", u);
for(int v = 1; v <= nodes; v++){
if(adj[u][v] && !visited[v]){
push(v);
}
}
}
}
}
int main() {
int nodes, edges;
scanf("%d%d", &nodes, &edges);
int u, v;
for(int i=0; i<MAX; i++){
for(int j=0; j<MAX; j++){
adj[i][j] = 0;
}
}
for(int i=0; i<edges; i++){
scanf("%d %d", &u, &v);
adj[u][v] = 1;
adj[v][u] = 1;
}
bfs(nodes, 1);
return 0;
}