Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: Catch negative edge weights in tree-version dijkstra #71

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions include/graaflib/algorithm/shortest_path.tpp
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,15 @@ dijkstra_shortest_paths(const graph<V, E, T>& graph,
}

for (const auto neighbor : graph.get_neighbors(current.id)) {
WEIGHT_T distance = current.dist_from_start +
get_weight(graph.get_edge(current.id, neighbor));
WEIGHT_T edge_weight = get_weight(graph.get_edge(current.id, neighbor));

if (edge_weight < 0) {
throw std::invalid_argument{fmt::format(
"Negative edge weight [{}] between vertices [{}] -> [{}].",
edge_weight, current.id, neighbor)};
}

WEIGHT_T distance = current.dist_from_start + edge_weight;

if (!shortest_paths.contains(neighbor) ||
distance < shortest_paths[neighbor].total_weight) {
Expand Down
37 changes: 37 additions & 0 deletions test/graaflib/algorithm/shortest_path_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,4 +493,41 @@ TYPED_TEST(DijkstraShortestPathSignedTypesTest, DijkstraNegativeWeight) {
},
std::invalid_argument);
}

TYPED_TEST(DijkstraShortestPathSignedTypesTest, DijkstraNegativeWeightTree) {
// GIVEN
using graph_t = typename TestFixture::graph_t;
using edge_t = typename TestFixture::edge_t;
using weight_t = decltype(get_weight(std::declval<edge_t>()));

graph_t graph{};

const auto vertex_id_1{graph.add_vertex(10)};
const auto vertex_id_2{graph.add_vertex(20)};
graph.add_edge(vertex_id_1, vertex_id_2, edge_t{static_cast<weight_t>(-1)});

// THEN
ASSERT_THROW(
{
try {
// Call the get_edge function for non-existing vertices
[[maybe_unused]] const auto path{
dijkstra_shortest_paths(graph, vertex_id_1)};
// If the above line doesn't throw an exception, fail the test
FAIL()
<< "Expected std::invalid_argument exception, but no exception "
"was thrown.";
} catch (const std::invalid_argument &ex) {
// Verify that the exception message contains the expected error
// message
EXPECT_EQ(
ex.what(),
fmt::format(
"Negative edge weight [{}] between vertices [{}] -> [{}].",
-1, vertex_id_1, vertex_id_2));
throw;
}
},
std::invalid_argument);
}
} // namespace graaf::algorithm