-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs.h
59 lines (45 loc) · 1.29 KB
/
bfs.h
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
#ifndef __BFS__
#define __BFS__
#include <queue>
using namespace std;
template<typename V, template<typename,typename> class E, typename D>
class BreadthFirstIterator {
public:
BreadthFirstIterator(Graph<V,E,D>* g) : graph(g) {
set<V*> vertices = graph->getAllVertices();
vQueue.push(*(vertices.begin()));
}
BreadthFirstIterator(Graph<V,E,D>* g, V* s) : graph(g), startVertex(s) {
vQueue.push(startVertex);
}
bool hasNext() {
return !vQueue.empty();
}
V* getNext() {
if (hasNext()) {
V* current = vQueue.front();
vQueue.pop();
extendVisit(current);
return current;
}
return NULL;
}
private:
Graph<V,E,D>* graph;
V* startVertex;
queue<V*> vQueue;
set<V*> markSet;
void extendVisit(V* current) {
set<V*> adjVertices = graph->verticesFrom(current);
typename set<V*>::iterator it;
for (it = adjVertices.begin(); it != adjVertices.end(); ++it) {
V* v = *it;
// not visited yet
if (markSet.find(v) == markSet.end()) {
vQueue.push(v);
markSet.insert(v);
}
}
}
};
#endif