AlgoPlus v0.1.0
Loading...
Searching...
No Matches
best_first.h
1#ifndef BEST_FIRST_H
2#define BEST_FIRST_H
3
4#ifdef __cplusplus
5#include <climits>
6#include <iostream>
7#include <queue>
8#include <unordered_map>
9#endif
10
14template <typename T> class best_first {
15 private:
16 std::unordered_map<T, std::vector<std::pair<T, double>>> adj;
17 std::unordered_map<T, double> nodes;
18
19 public:
28 explicit best_first(std::unordered_map<T, std::vector<std::pair<T, double>>> v = {},
29 std::unordered_map<T, double> nodes = {}) {
30 try {
31 if ((!v.empty() && nodes.empty()) || (v.empty() && !nodes.empty())) {
32 throw std::logic_error("You have to provide two non-empty maps");
33 }
34 if (!v.empty() && !nodes.empty()) {
35 this->adj = v;
36 this->nodes = nodes;
37 }
38 } catch (std::logic_error& e) {
39 std::cerr << e.what() << '\n';
40 }
41 }
42
48 inline void insert_node(T u, double val) { nodes[u] = val; }
49
57 inline bool has_edge(T u, T v) {
58 if (adj.find(u) != adj.end()) {
59 for (std::pair<T, double>& x : adj[u]) {
60 if (x.first == v) {
61 return true;
62 }
63 }
64 }
65 return false;
66 }
67
73 inline void add_edge(T u, T v) {
74 try {
75 if (nodes.find(u) != nodes.end() && nodes.find(v) != nodes.end()) {
76 adj[u].push_back(std::make_pair(v, nodes[v]));
77 } else {
78 throw std::logic_error("One of the two nodes that passed to the "
79 "function do not exist in the graph");
80 }
81 } catch (std::logic_error& e) {
82 std::cerr << e.what() << '\n';
83 }
84 }
85
93 inline bool search(T start, T end) {
94 if (adj.empty()) {
95 return false;
96 }
97 std::unordered_map<T, bool> visited;
98 std::priority_queue<std::pair<T, double>, std::vector<std::pair<T, double>>,
99 std::greater<std::pair<T, double>>>
100 q;
101 q.push({start, nodes[start]});
102 visited[start] = true;
103 while (!q.empty()) {
104 int64_t size = q.size();
105 for (int64_t i = 0; i < size; i++) {
106 std::pair<T, double> current = q.top();
107 if (current.first == end) {
108 return true;
109 }
110 q.pop();
111 for (std::pair<T, double>& x : adj[current.first]) {
112 if (visited.find(x.first) == visited.end() &&
113 x.second <= nodes[current.first]) {
114 visited[x.first] = true;
115 q.push({x.first, nodes[x.first]});
116 }
117 }
118 }
119 }
120 return false;
121 }
122};
123
124#endif
void add_edge(T u, T v)
add_edge function
Definition best_first.h:73
best_first(std::unordered_map< T, std::vector< std::pair< T, double > > > v={}, std::unordered_map< T, double > nodes={})
best_first constructor
Definition best_first.h:28
bool has_edge(T u, T v)
has_edge function
Definition best_first.h:57
void insert_node(T u, double val)
insert_node function
Definition best_first.h:48
bool search(T start, T end)
search function
Definition best_first.h:93