30 std::function<int64_t(
int,
int)> graph,
31 int64_t disconnected_distance)
32 : node_count_(node_count),
33 start_node_(start_node),
34 graph_(
std::move(graph)),
35 disconnected_distance_(disconnected_distance),
36 distance_(new int64_t[node_count_]),
37 predecessor_(new int[node_count_]) {}
44 void FindPath(
int dest, std::vector<int>*
nodes)
const;
46 const int node_count_;
47 const int start_node_;
48 std::function<int64_t(
int,
int)> graph_;
49 const int64_t disconnected_distance_;
50 std::unique_ptr<int64_t[]> distance_;
51 std::unique_ptr<int[]> predecessor_;
54void BellmanFord::Initialize() {
55 for (
int i = 0; i < node_count_; i++) {
59 distance_[start_node_] = 0;
62void BellmanFord::Update() {
63 for (
int i = 0; i < node_count_ - 1; i++) {
64 for (
int u = 0; u < node_count_; u++) {
65 for (
int v = 0; v < node_count_; v++) {
66 const int64_t graph_u_v = graph_(u, v);
67 if (graph_u_v != disconnected_distance_) {
68 const int64_t other_distance = distance_[u] + graph_u_v;
69 if (distance_[v] > other_distance) {
70 distance_[v] = other_distance;
79bool BellmanFord::Check()
const {
80 for (
int u = 0; u < node_count_; u++) {
81 for (
int v = 0; v < node_count_; v++) {
82 const int graph_u_v = graph_(u, v);
83 if (graph_u_v != disconnected_distance_) {
84 if (distance_[v] > distance_[u] + graph_u_v) {
93void BellmanFord::FindPath(
int dest, std::vector<int>*
nodes)
const {
96 while (predecessor_[j] != -1) {
97 nodes->push_back(predecessor_[j]);
111 FindPath(end_node,
nodes);
116 std::function<int64_t(
int,
int)> graph,
117 int64_t disconnected_distance,
118 std::vector<int>*
nodes) {
119 BellmanFord bf(node_count, start_node, std::move(graph),
120 disconnected_distance);
bool ShortestPath(int end_node, std::vector< int > *nodes)
BellmanFord(int node_count, int start_node, std::function< int64_t(int, int)> graph, int64_t disconnected_distance)
static constexpr int64_t kInfinity
Collection of objects used to extend the Constraint Solver library.
bool BellmanFordShortestPath(int node_count, int start_node, int end_node, std::function< int64_t(int, int)> graph, int64_t disconnected_distance, std::vector< int > *nodes)