-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.cpp
More file actions
74 lines (66 loc) · 1.04 KB
/
bfs.cpp
File metadata and controls
74 lines (66 loc) · 1.04 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
#include<stdio.h>
#include<vector>
#include<queue>
using namespace std;
#define SZ 100
#define INF 9867684
#define NIL -1
#define WHITE 0
#define GRAY 1
#define BLACK 2
int nV, nE;
int color[SZ];
queue<int> Q;
int d[SZ], pi[SZ];
vector<int> edge[SZ];
void bfs(int S){
int i, u, v;
for(u=1; u<=nV; u++){
color[u] = WHITE;
d[u] = INF;
pi[u] = NIL;
}
color[S] = GRAY;
d[S] = 0;
pi[S] = NIL;
Q.push(S);
while( !Q.empty() ){
u = Q.front();
Q.pop();
for(i=0; i<edge[u].size(); i++){
v = edge[u][i];
if( color[v] == WHITE ){
color[v] = GRAY;
d[v] = d[u] + 1;
pi[v] = u;
Q.push(v);
}
}
color[u] = BLACK;
}
}
void print_path(int u){
if( pi[u] == -1 ){
printf("%d", u);
return;
}
print_path(pi[u]);
printf(" %d", u);
}
void input(){
int i, u, v;
printf("Insert number of node and number of edges :: ");
scanf("%d%d", &nV, &nE);
puts("Insert edges :: ");
for(i=0; i<nE; i++){
scanf("%d%d", &u, &v);
edge[u].push_back(v);
}
}
int main(){
int S;
input();
scanf("%d", &S);
bfs(S);
return 0;
}