openGPMP
Open Source Mathematics Package
Classes | Functions | Variables
ospf.cpp File Reference
#include <iostream>
#include <limits>
#include <queue>
#include <vector>

Go to the source code of this file.

Classes

struct  Edge
 

Functions

void dijkstra (const std::vector< std::vector< Edge >> &graph, int source, std::vector< int > &distances, std::vector< int > &parents)
 
int main ()
 

Variables

const int INF = std::numeric_limits<int>::max()
 

Function Documentation

◆ dijkstra()

void dijkstra ( const std::vector< std::vector< Edge >> &  graph,
int  source,
std::vector< int > &  distances,
std::vector< int > &  parents 
)

Definition at line 53 of file ospf.cpp.

56  {
57  int n = graph.size();
58  distances.assign(n, INF);
59  parents.assign(n, -1);
60 
61  distances[source] = 0;
62  std::priority_queue<std::pair<int, int>,
63  std::vector<std::pair<int, int>>,
64  std::greater<std::pair<int, int>>>
65  pq;
66  pq.push(std::make_pair(0, source));
67 
68  while (!pq.empty()) {
69  int current = pq.top().second;
70  int distance = pq.top().first;
71  pq.pop();
72 
73  if (distance > distances[current])
74  continue;
75 
76  for (const Edge &edge : graph[current]) {
77  int neighbor = edge.to;
78  int new_distance = distance + edge.weight;
79 
80  if (new_distance < distances[neighbor]) {
81  distances[neighbor] = new_distance;
82  parents[neighbor] = current;
83  pq.push(std::make_pair(new_distance, neighbor));
84  }
85  }
86  }
87 }
const int INF
Definition: ospf.cpp:44
Definition: ospf.cpp:47

References INF.

Referenced by main().

◆ main()

int main ( void  )

Definition at line 89 of file ospf.cpp.

89  {
90  int n = 4; // Number of nodes
91  std::vector<std::vector<Edge>> graph(n);
92 
93  graph[0].push_back({1, 2});
94  graph[0].push_back({2, 5});
95  graph[1].push_back({2, 1});
96  graph[1].push_back({3, 3});
97  graph[2].push_back({3, 1});
98 
99  int source = 0;
100  std::vector<int> distances, parents;
101  dijkstra(graph, source, distances, parents);
102 
103  int destination = 3;
104  std::cout << "Shortest distance from " << source << " to " << destination
105  << ": " << distances[destination] << std::endl;
106  std::cout << "Shortest path: ";
107  for (int node = destination; node != -1; node = parents[node])
108  std::cout << node << " ";
109  std::cout << std::endl;
110 
111  return 0;
112 }
void dijkstra(const std::vector< std::vector< Edge >> &graph, int source, std::vector< int > &distances, std::vector< int > &parents)
Definition: ospf.cpp:53

References dijkstra().

Variable Documentation

◆ INF

const int INF = std::numeric_limits<int>::max()

Definition at line 44 of file ospf.cpp.

Referenced by dijkstra().