/
DijkstraShortestPathcs.cs
66 lines (59 loc) · 2.08 KB
/
DijkstraShortestPathcs.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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenNLP.Tools.Util;
namespace OpenNLP.Tools.Graphs
{
public static class DijkstraShortestPath
{
public static /*<V, E>*/ List<V> GetShortestPath<V, E>(IGraph<V, E> graph, V node1, V node2, bool directionSensitive)
{
if (node1.Equals(node2))
{
//return Collections.singletonList(node2);
return new List<V>() {node2};
}
Set<V> visited = new Util.HashSet<V>();
var previous = new Dictionary<V, V>();
var unsettledNodes = new BinaryHeapPriorityQueue<V>();
unsettledNodes.Add(node1, 0);
while (unsettledNodes.Size() > 0)
{
var distance = unsettledNodes.GetPriority();
var u = unsettledNodes.RemoveFirst();
visited.Add(u);
if (u.Equals(node2))
break;
unsettledNodes.Remove(u);
var candidates = ((directionSensitive) ? graph.GetChildren(u) : new ReadOnlyCollection<V>(graph.GetNeighbors(u)));
foreach (var candidate in candidates)
{
var alt = distance - 1;
// nodes not already present will have a priority of -inf
if (alt > unsettledNodes.GetPriority(candidate) && !visited.Contains(candidate))
{
unsettledNodes.RelaxPriority(candidate, alt);
previous[candidate] = u;
}
}
}
if (!previous.ContainsKey(node2))
return null;
var path = new List<V>
{
node2
};
var n = node2;
while (previous.ContainsKey(n))
{
path.Add(previous[n]);
n = previous[n];
}
path.Reverse();
return path;
}
}
}