AIToolbox
A library that offers tools for AI problem solving.
APSP.hpp
Go to the documentation of this file.
1 #ifndef AI_TOOLBOX_FACTORED_APSP_HEADER_FILE
2 #define AI_TOOLBOX_FACTORED_APSP_HEADER_FILE
3 
6 
7 namespace AIToolbox::Factored {
8  template <typename Factor>
9  auto buildAdjacencyList(const Action & A, const FactorGraph<Factor> & graph);
10 
27  template <typename Factor>
28  size_t APSP(const FactorGraph<Factor> & graph) {
29  // We simply perform BFS on each node of the graph for its max distance,
30  // return the min out of all.
31 
32  const auto A = graph.variableSize();
33  size_t retval = 0;
34 
35  std::vector<size_t> distances(A);
36  std::vector<size_t> front;
37  front.reserve(A);
38 
39  const auto adjacencyList = buildAdjacencyList(graph);
40 
41  for (size_t a = 0; a < A; ++a) {
42  std::fill(std::begin(distances), std::end(distances), 0);
43  front.clear();
44 
45  front.push_back(a);
46  distances[a] = A;
47 
48  for (size_t i = 0; i < front.size(); ++i) {
49  const auto a2 = front[i];
50  const auto d = (distances[a2] == A) ? 0 : distances[a2];
51 
52  for (auto n : adjacencyList[a2]) {
53  if (distances[n] == 0) {
54  distances[n] = d + 1;
55  front.push_back(n);
56  }
57  }
58  }
59 
60  distances[a] = 0;
61  retval = std::max(retval, *std::max_element(std::begin(distances), std::end(distances)));
62  }
63  return retval;
64  }
65 
78  template <typename Factor>
80  const auto A = graph.variableSize();
81 
82  std::vector<std::vector<size_t>> adjacencyList;
83  adjacencyList.resize(A);
84 
85  for (const auto & f : graph) {
86  const auto & tag = f.getVariables();
87  for (auto a : tag)
88  adjacencyList[a].insert(std::end(adjacencyList[a]), std::begin(tag), std::end(tag));
89  }
90 
91  for (size_t a = 0; a < A; ++a) {
92  auto & al = adjacencyList[a];
93  auto begin = std::begin(al), end = std::end(al);
94 
95  std::sort(begin, end);
96  end = std::unique(begin, end);
97  end = std::remove(begin, end, a);
98  al.erase(end, std::end(al));
99  }
100 
101  return adjacencyList;
102  }
103 }
104 
105 #endif
AIToolbox::Factored::buildAdjacencyList
auto buildAdjacencyList(const Action &A, const FactorGraph< Factor > &graph)
AIToolbox::Factored::FactorGraph::variableSize
size_t variableSize() const
This function returns the number of variables still in the graph.
Definition: FactorGraph.hpp:429
AIToolbox::Factored::FactorGraph
This class offers a minimal interface to manager a factor graph.
Definition: FactorGraph.hpp:31
AIToolbox::Factored
Definition: GraphUtils.hpp:12
Types.hpp
AIToolbox::Factored::APSP
size_t APSP(const FactorGraph< Factor > &graph)
This function solves the APSP problem for the provided graph.
Definition: APSP.hpp:28
FactorGraph.hpp
AIToolbox::Factored::Action
Factors Action
Definition: Types.hpp:69