forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DijkstraAllPairsShortestPaths.cs
83 lines (66 loc) · 2.95 KB
/
DijkstraAllPairsShortestPaths.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/***
* Computes Dijktra's shortest paths for all pairs of vertices in a graph.
* This is a wrapper class that applies single-source dijkstra shortest paths (DijkstraShortestPaths<TG, TV>)
* to all vertices of a graph and saves the results in a dictionary index by the vertices.
*/
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Algorithms.Common;
using DataStructures.Graphs;
using DataStructures.Heaps;
namespace Algorithms.Graphs
{
public class DijkstraAllPairsShortestPaths<TGraph, TVertex>
where TGraph : IGraph<TVertex>, IWeightedGraph<TVertex>
where TVertex : IComparable<TVertex>
{
/// <summary>
/// INSTANCE VARIABLES
/// </summary>
Dictionary<TVertex, DijkstraShortestPaths<TGraph, TVertex>> _allPairsDjkstra;
/// <summary>
/// CONSTRUCTOR
/// </summary>
public DijkstraAllPairsShortestPaths(TGraph Graph)
{
if (Graph == null)
throw new ArgumentNullException();
// Initialize the all pairs dictionary
_allPairsDjkstra = new Dictionary<TVertex, DijkstraShortestPaths<TGraph, TVertex>>();
var vertices = Graph.Vertices;
foreach (var vertex in vertices)
{
var dijkstra = new DijkstraShortestPaths<TGraph, TVertex>(Graph, vertex);
_allPairsDjkstra.Add(vertex, dijkstra);
}
}
/// <summary>
/// Determines whether there is a path from source vertex to destination vertex.
/// </summary>
public bool HasPath(TVertex source, TVertex destination)
{
if (!_allPairsDjkstra.ContainsKey(source) || !_allPairsDjkstra.ContainsKey(destination))
throw new Exception("Either one of the vertices or both of them don't belong to Graph.");
return _allPairsDjkstra[source].HasPathTo(destination);
}
/// <summary>
/// Returns the distance between source vertex and destination vertex.
/// </summary>
public long PathDistance(TVertex source, TVertex destination)
{
if (!_allPairsDjkstra.ContainsKey(source) || !_allPairsDjkstra.ContainsKey(destination))
throw new Exception("Either one of the vertices or both of them don't belong to Graph.");
return _allPairsDjkstra[source].DistanceTo(destination);
}
/// <summary>
/// Returns an enumerable collection of nodes that specify the shortest path from source vertex to destination vertex.
/// </summary>
public IEnumerable<TVertex> ShortestPath(TVertex source, TVertex destination)
{
if (!_allPairsDjkstra.ContainsKey(source) || !_allPairsDjkstra.ContainsKey(destination))
throw new Exception("Either one of the vertices or both of them don't belong to Graph.");
return _allPairsDjkstra[source].ShortestPathTo(destination);
}
}
}