BellmanFord.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. namespace PathfindingPCL
  4. {
  5. public class BellmanFord : Algorithm
  6. {
  7. public BellmanFord(Graph _graph, IHM _ihm) : base(_graph, _ihm) {}
  8. protected override void Run()
  9. {
  10. // Initialisation
  11. bool distanceChanged = true;
  12. int i = 0;
  13. List<Arc> arcsList = graph.ArcsList();
  14. // Boucle principale
  15. int nbLoopMax = graph.NodesCount() - 1;
  16. while (i < nbLoopMax && distanceChanged)
  17. {
  18. distanceChanged = false;
  19. foreach (Arc arc in arcsList)
  20. {
  21. if (arc.FromNode.DistanceFromBegin + arc.Cost < arc.ToNode.DistanceFromBegin)
  22. {
  23. arc.ToNode.DistanceFromBegin = arc.FromNode.DistanceFromBegin + arc.Cost;
  24. arc.ToNode.Precursor = arc.FromNode;
  25. distanceChanged = true;
  26. }
  27. }
  28. i++;
  29. }
  30. // Test si boucle négative
  31. foreach (Arc arc in arcsList)
  32. {
  33. if (arc.FromNode.DistanceFromBegin + arc.Cost < arc.ToNode.DistanceFromBegin)
  34. {
  35. // Impossible de trouver un chemin
  36. throw new Exception();
  37. }
  38. }
  39. }
  40. }
  41. }