AStar.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace PathfindingPCL
  4. {
  5. public class AStar : Algorithm
  6. {
  7. public AStar(Graph _graph, IHM _ihm) : base(_graph, _ihm) { }
  8. protected override void Run()
  9. {
  10. // Initialisation
  11. graph.ComputeEstimatedDistanceToExit();
  12. List<Node> nodesToVisit = graph.NodesList();
  13. bool exitReached = false;
  14. // Boucle principale
  15. while (nodesToVisit.Count != 0 && !exitReached)
  16. {
  17. Node currentNode = nodesToVisit.FirstOrDefault();
  18. foreach (Node newNode in nodesToVisit)
  19. {
  20. if ((newNode.DistanceFromBegin + newNode.EstimatedDistance) < (currentNode.DistanceFromBegin + currentNode.EstimatedDistance))
  21. {
  22. currentNode = newNode;
  23. }
  24. }
  25. if (currentNode == graph.ExitNode())
  26. {
  27. // Sortie trouvée : on a fini
  28. exitReached = true;
  29. }
  30. else
  31. {
  32. // On applique tous les arcs sortant du noeud
  33. List<Arc> arcsFromCurrentNode = graph.ArcsList(currentNode);
  34. foreach (Arc arc in arcsFromCurrentNode)
  35. {
  36. if (arc.FromNode.DistanceFromBegin + arc.Cost < arc.ToNode.DistanceFromBegin)
  37. {
  38. arc.ToNode.DistanceFromBegin = arc.FromNode.DistanceFromBegin + arc.Cost;
  39. arc.ToNode.Precursor = arc.FromNode;
  40. }
  41. }
  42. nodesToVisit.Remove(currentNode);
  43. }
  44. }
  45. }
  46. }
  47. }