-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreadth_first_search.h
More file actions
103 lines (88 loc) · 2.4 KB
/
Copy pathbreadth_first_search.h
File metadata and controls
103 lines (88 loc) · 2.4 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#ifndef CPP_ALGORITHM_BREADTH_FIRST_SEARCH_H
#define CPP_ALGORITHM_BREADTH_FIRST_SEARCH_H
#include <queue>
#include <set>
#include <vector>
namespace Bfs
{
enum VisitStatus
{
Unvisited,
Visited,
Finished
};
struct Vertex
{
explicit Vertex(const char id)
: id(id), neighbors(std::set<Vertex*>()), predecessor(nullptr), visit(Unvisited), distance(0)
{
}
char id;
std::set<Vertex*> neighbors;
Vertex* predecessor;
VisitStatus visit;
int distance;
};
class Graph
{
public:
/**
* \brief Breadth first search algorithm.
* \details A search algorithm that traverses a graph layer by layer.
* \param start starting vertex
* \param goal goal vertex
* \return goal vertex
*/
static Vertex* BreadthFirstSearch(Vertex& start, const Vertex& goal);
void AddVertex(Vertex& v);
void AddEdge(Vertex& u, Vertex& v);
std::vector<Vertex*> vertices;
std::vector<std::tuple<Vertex*, Vertex*>> adjacency_list;
};
}
// ----------------------------------------------------------------------------
inline Bfs::Vertex* Bfs::Graph::BreadthFirstSearch(Vertex& start, const Vertex& goal)
{
if (start.id == goal.id)
{
start.visit = Finished;
return &start;
}
start.visit = Visited;
auto queue = std::queue<Vertex*>{};
queue.push(&start);
while (queue.empty() == false)
{
const auto vertex = queue.front();
queue.pop();
for (auto v : vertex->neighbors)
{
if (v->visit == Unvisited)
{
v->visit = Visited;
v->distance = vertex->distance + 1;
v->predecessor = vertex;
queue.push(v);
if (v->id == goal.id)
{
return v;
}
}
}
vertex->visit = Finished;
}
return {};
}
// ----------------------------------------------------------------------------
inline void Bfs::Graph::AddVertex(Vertex& v)
{
vertices.push_back(&v);
}
// ----------------------------------------------------------------------------
inline void Bfs::Graph::AddEdge(Vertex& u, Vertex& v)
{
adjacency_list.emplace_back(&u, &v);
u.neighbors.insert(&v);
// v.neighbors.insert(&u);
}
#endif