Skip to content

Commit

Permalink
Added dijkstra's cp version
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Oct 16, 2024
1 parent d1df6ba commit f3563d6
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/algorithms/searching/shortest_path.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#ifndef SHORTEST_PATH_H
#define SHORTEST_PATH_H


#ifdef __cplusplus
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#endif

/**
* @brief shortest path algorithm. A more CP friendly version to be used in competitions
* @param adj: the input graph
* @param n: the total nodes in the graph(this is used for continuous nodes, i.e 1,...,n)
* @param start: starting node
* @param end: ending node
* @return vector<int>: the shortest distances for each node n_i to end
*/
int shortest_path(std::unordered_map<int, std::vector<std::pair<int, int> > > &adj, int n, int start, int end) {
std::vector<int> dist(n, std::numeric_limits<int>::max());

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int> >, std::greater<std::pair<int, int> > > q;
q.push(std::make_pair(0, start));
dist[start] = 0;

while(!q.empty()) {
int currentNode = q.top().second;
int currentDist = q.top().first;
q.pop();

if(currentDist > dist[currentNode]) {
continue;
}
for(std::pair<int, int> &edge: adj[currentNode]) {
if(currentDist + edge.second < dist[edge.first]) {
dist[edge.first] = currentDist + edge.second;
q.push(std::make_pair(dist[edge.first], edge.first));
}
}
}

return (dist[end] != std::numeric_limits<int>::max()) ? dist[end] : -1;
}


#endif
37 changes: 37 additions & 0 deletions tests/algorithms/searching/shortest_path.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include "../../../src/algorithms/searching/shortest_path.h"
#include "../../../third_party/catch.hpp"

TEST_CASE("Testing dijkstra's algorithm [1]") {
std::unordered_map<int, std::vector<std::pair<int, int> > > adj;
adj[0].push_back({1, 10});
adj[2].push_back({3, 8});
adj[1].push_back({2, 6});
adj[0].push_back({3, 4});

REQUIRE(shortest_path(adj, 4, 0, 3) == 4);
}

TEST_CASE("Testing dijkstra's algorithm [2]") {

std::unordered_map<int, std::vector<std::pair<int, int> > > adj;

adj[0].push_back({1, 0});
adj[1].push_back({2, 2});
adj[2].push_back({5, 3});
adj[1].push_back({5, 1});
adj[3].push_back({2, 4});
REQUIRE(shortest_path(adj, 6, 0, 5) == 1);
}

TEST_CASE("Testing dijkstra's algorithm [3]") {
std::unordered_map<int, std::vector<std::pair<int, int> > > adj;

adj[0].push_back({0, 0});
REQUIRE(shortest_path(adj, 5, 0, 4) == -1);

adj[1].push_back({2, 1});
adj[2].push_back({3, 4});
adj[3].push_back({4, 5});
adj[1].push_back({4, 6});
REQUIRE(shortest_path(adj, 5, 1, 4) == 6);
}

0 comments on commit f3563d6

Please sign in to comment.