-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph Theory BFS Implementation.cpp
More file actions
74 lines (63 loc) · 1.23 KB
/
Copy pathGraph Theory BFS Implementation.cpp
File metadata and controls
74 lines (63 loc) · 1.23 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<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
#define WHITE 1
#define GRAY 2
#define BLACK 3
int adj[100][100];
int color[100];
int parent[100];
int dis[100];
int n, e;
void bfs(int startNode)
{
for(int i=0; i<n; i++)
{
color[i] = WHITE;
dis[i] = INT_MIN;
parent[i] = -1;
}
dis[startNode] = 0;
parent[startNode] = -1;
queue <int> q;
q.push(startNode);
while( ! q.empty() )
{
int x;
x = q.front();
q.pop();
color[x] = GRAY;
cout<<x<<" ";
for(int i=0; i<n; i++)
{
if(adj[x][i] == 1)
{
if(color[i] == WHITE)
{
dis[i] = dis[x]+1;
parent[i] = x;
q.push(i);
}
}
}
color[x] = BLACK;
}
}
int main()
{
freopen("input1.txt","r", stdin);
cin>>n>>e;
int n1, n2;
for(int i=0; i<e; i++)
{
cin>>n1>>n2;
adj[n1][n2] = 1;
adj[n2][n1] = 1;
}
bfs(0);
cout<<endl;
cout<<parent[5]<<endl;
cout<<dis[7]<<endl;
return 0;
}