28 std::function<int64_t(
int,
int)> graph,
29 int64_t disconnected_distance)
30 : node_count_(node_count),
31 start_node_(start_node),
32 graph_(std::move(graph)),
33 disconnected_distance_(disconnected_distance),
34 distance_(new int64_t[node_count_]),
35 predecessor_(new int[node_count_]) {}
42 void FindPath(
int dest, std::vector<int>*
nodes)
const;
44 const int node_count_;
45 const int start_node_;
46 std::function<int64_t(
int,
int)> graph_;
47 const int64_t disconnected_distance_;
48 std::unique_ptr<int64_t[]> distance_;
49 std::unique_ptr<int[]> predecessor_;
52 void BellmanFord::Initialize() {
53 for (
int i = 0; i < node_count_; i++) {
57 distance_[start_node_] = 0;
60 void BellmanFord::Update() {
61 for (
int i = 0; i < node_count_ - 1; i++) {
62 for (
int u = 0; u < node_count_; u++) {
63 for (
int v = 0; v < node_count_; v++) {
64 const int64_t graph_u_v = graph_(u, v);
65 if (graph_u_v != disconnected_distance_) {
66 const int64_t other_distance = distance_[u] + graph_u_v;
67 if (distance_[v] > other_distance) {
68 distance_[v] = other_distance;
77 bool BellmanFord::Check()
const {
78 for (
int u = 0; u < node_count_; u++) {
79 for (
int v = 0; v < node_count_; v++) {
80 const int graph_u_v = graph_(u, v);
81 if (graph_u_v != disconnected_distance_) {
82 if (distance_[v] > distance_[u] + graph_u_v) {
91 void BellmanFord::FindPath(
int dest, std::vector<int>*
nodes)
const {
94 while (predecessor_[j] != -1) {
95 nodes->push_back(predecessor_[j]);
109 FindPath(end_node,
nodes);
114 std::function<int64_t(
int,
int)> graph,
115 int64_t disconnected_distance,
116 std::vector<int>*
nodes) {
117 BellmanFord bf(node_count, start_node, std::move(graph),
118 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
static const int64_t kint64max
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)