Skip to content

Commit cd150ad

Browse files
committed
start implementing graph immutability
1 parent 39f4470 commit cd150ad

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using Dijkstra.NET.Contract;
4+
using Dijkstra.NET.Extensions;
5+
using Dijkstra.NET.Model;
6+
using Dijkstra.NET.Utility;
7+
8+
namespace Dijkstra.NET.ShortestPath
9+
{
10+
public class ImmutableDijkstra<T, TEdgeCustom> : Dijkstra<T, TEdgeCustom> where TEdgeCustom : IEquatable<TEdgeCustom>
11+
{
12+
public ImmutableDijkstra(IGraph<T, TEdgeCustom> graph) : base(graph)
13+
{
14+
}
15+
16+
public override IShortestPathResult Process(uint @from, uint to)
17+
{
18+
var result = new DijkstraResult(from, to);
19+
Graph[from].Distance = 0;
20+
var q = new SortedSet<INode<T, TEdgeCustom>>(new[] { Graph[from] }, new NodeComparer<T, TEdgeCustom>());
21+
var current = new HashSet<uint>();
22+
23+
while (q.Count > 0)
24+
{
25+
INode<T, TEdgeCustom> u = q.Deque();
26+
current.Remove(u.Key);
27+
28+
if (u.Key == to)
29+
{
30+
result.Distance = u.Distance;
31+
break;
32+
}
33+
34+
for (int i = 0; i < u.Children.Count; i++)
35+
{
36+
Edge<T, TEdgeCustom> e = u.Children[i];
37+
38+
if (e.Node.Distance > u.Distance + e.Cost)
39+
{
40+
if (current.Contains(e.Node.Key))
41+
q.Remove(e.Node);
42+
43+
e.Node.Distance = u.Distance + e.Cost;
44+
q.Add(e.Node);
45+
current.Add(e.Node.Key);
46+
result.Path[e.Node.Key] = u.Key;
47+
}
48+
}
49+
}
50+
51+
return result;
52+
}
53+
}
54+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace Dijkstra.NET.ShortestPath.Model
2+
{
3+
public struct ShortPathJob
4+
{
5+
public uint NodeKey { get; set; }
6+
7+
public int Distance { get; set; }
8+
9+
}
10+
}

0 commit comments

Comments
 (0)