-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.cpp
61 lines (48 loc) · 1.04 KB
/
bfs.cpp
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
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#define MAX 100000
#define UNVISITED -1
using namespace std;
int component[MAX];
vector<int> grafo[MAX];
/**
*
* Graph is unweighted,
* or all distances are one between two vertices adjacent.
*
*/
// Breath First Search
void bfs(int v)
{
queue<int> q;
// q : v
q.push(v);
component[v] = v;
// while is not empty
while(!q.empty())
{
int no = q.front();
q.pop();
// for every neighboor of no
for(int i = 0; i < grafo[no].size(); ++i)
{
// if the it has been no visited insert neighboors of node v in queue q
if(component[grafo[no][i]] == UNVISITED)
{
component[grafo[no][i]] = component[no];
q.push(grafo[no][i]);
}
}
}
}
int main()
{
// start vertice (node)
int v = 0;
// mark all nodes with unvisited
memset(component, UNVISITED, sizeof component);
bfs(v);
return 0;
}