-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.hpp
77 lines (66 loc) · 1.88 KB
/
DFS.hpp
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
75
76
77
#pragma once
#include "Graph.hpp"
#include <functional>
#include <stack>
#include <queue>
template<typename V,typename E>
void DFS(const Graph<V,E>&g,std::size_t startID,
std::function<void(const V&) > f)
{
std::size_t verticesNumber = g.nrOfVertices();
if(startID>=verticesNumber)
throw std::runtime_error(std::string("[DFS] Incorrect startID:")
+std::to_string(startID));
std::vector<bool> visitedVertices(verticesNumber,false);
std::stack<std::size_t> s1;
s1.push(startID);
while(!s1.empty())
{
std::size_t vId = s1.top();
visitedVertices[vId] = true;
f(g.vertexData(vId));
s1.pop();
std::size_t iter = verticesNumber;
while(iter>0)
{
--iter;
if(!visitedVertices[iter])
{
if(g.edgeExist(vId,iter))
{
s1.push(iter);
}
}
}
}
}
template<typename V,typename E>
void BFS(const Graph<V,E>&g,std::size_t startID,
std::function<void(const V&) > f)
{
std::size_t verticesNumber = g.nrOfVertices();
if(startID>=verticesNumber)
throw std::runtime_error(std::string("[BFS] Incorrect startID:")
+std::to_string(startID));
std::vector<bool> visitedVertices(verticesNumber,false);
visitedVertices.resize(verticesNumber);
std::queue<std::size_t> q1;
q1.push(startID);
while(!q1.empty())
{
std::size_t vId = q1.front();
visitedVertices[vId] = true;
f(g.vertexData(vId));
q1.pop();
for(std::size_t iter=0; iter < verticesNumber; ++iter)
{
if(!visitedVertices[iter])
{
if(g.edgeExist(vId,iter))
{
q1.push(iter);
}
}
}
}
}