Dijkstra.cs 1.6 KB

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