Satsuma
a delicious .NET graph library
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Properties Pages
AStar.cs
Go to the documentation of this file.
1 #region License
2 /*This file is part of Satsuma Graph Library
3 Copyright © 2013 Balázs Szalkai
4 
5 This software is provided 'as-is', without any express or implied
6 warranty. In no event will the authors be held liable for any damages
7 arising from the use of this software.
8 
9 Permission is granted to anyone to use this software for any purpose,
10 including commercial applications, and to alter it and redistribute it
11 freely, subject to the following restrictions:
12 
13  1. The origin of this software must not be misrepresented; you must not
14  claim that you wrote the original software. If you use this software
15  in a product, an acknowledgment in the product documentation would be
16  appreciated but is not required.
17 
18  2. Altered source versions must be plainly marked as such, and must not be
19  misrepresented as being the original software.
20 
21  3. This notice may not be removed or altered from any source
22  distribution.*/
23 #endregion
24 
25 using System;
26 using System.Collections.Generic;
27 using System.Linq;
28 
29 namespace Satsuma
30 {
56  public sealed class AStar
57  {
59  public IGraph Graph { get; private set; }
61  public Func<Arc, double> Cost { get; private set; }
73  public Func<Node, double> Heuristic { get; private set; }
74 
75  private Dijkstra dijkstra;
76 
80  public AStar(IGraph graph, Func<Arc, double> cost, Func<Node, double> heuristic)
81  {
82  Graph = graph;
83  Cost = cost;
84  Heuristic = heuristic;
85 
86  dijkstra = new Dijkstra(Graph, arc => Cost(arc) - Heuristic(Graph.U(arc)) + Heuristic(Graph.V(arc)),
87  DijkstraMode.Sum);
88  }
89 
90  private Node CheckTarget(Node node)
91  {
92  if (node != Node.Invalid && Heuristic(node) != 0)
93  throw new ArgumentException("Heuristic is nonzero for a target");
94  return node;
95  }
96 
99  public void AddSource(Node node)
100  {
101  dijkstra.AddSource(node, Heuristic(node));
102  }
103 
108  public Node RunUntilReached(Node target)
109  {
110  return CheckTarget(dijkstra.RunUntilFixed(target));
111  }
112 
116  public Node RunUntilReached(Func<Node, bool> isTarget)
117  {
118  return CheckTarget(dijkstra.RunUntilFixed(isTarget));
119  }
120 
125  public double GetDistance(Node node)
126  {
127  CheckTarget(node);
128  return dijkstra.Fixed(node) ? dijkstra.GetDistance(node) : double.PositiveInfinity;
129  }
130 
134  public IPath GetPath(Node node)
135  {
136  CheckTarget(node);
137  if (!dijkstra.Fixed(node)) return null;
138  return dijkstra.GetPath(node);
139  }
140  }
141 }