-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
81b6259
commit e0ad6d0
Showing
3 changed files
with
96 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using Dijkstra.NET.Graph; | ||
|
||
namespace Dijkstra.NET.ShortestPath | ||
{ | ||
internal static class AStar | ||
{ | ||
public static ShortestPathResult GetShortestPath(IDijkstraGraph graph, uint from, uint to, Func<uint,uint,int> heuristic, int depth) | ||
{ | ||
var path = new Dictionary<uint, uint>(); | ||
var distance = new Dictionary<uint, int> {[from] = 0}; | ||
var d = new Dictionary<uint, int> {[from] = 0}; | ||
var q = new SortedSet<uint>(new[] {from}, new NodeComparer(distance, heuristic)); | ||
var current = new HashSet<uint>(); | ||
|
||
int Distance(uint key) | ||
{ | ||
return distance.ContainsKey(key) ? distance[key] : Int32.MaxValue; | ||
} | ||
|
||
do | ||
{ | ||
uint u = q.Deque(); | ||
|
||
if (u == to) | ||
{ | ||
return new ShortestPathResult(from, to, distance[u], path); | ||
} | ||
|
||
current.Remove(u); | ||
|
||
if (depth == d[u]) | ||
{ | ||
continue; | ||
} | ||
|
||
graph[u]((node, cost) => | ||
{ | ||
if (Distance(node) > Distance(u) + cost) | ||
{ | ||
if (current.Contains(node)) | ||
{ | ||
q.Remove(node); | ||
} | ||
|
||
distance[node] = Distance(u) + cost; | ||
q.Add(node); | ||
current.Add(node); | ||
path[node] = u; | ||
d[node] = d[u] + 1; | ||
} | ||
}); | ||
|
||
} while (q.Count > 0 && depth > 0); | ||
|
||
return new ShortestPathResult(from, to); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters