Advertisement
pevel

Untitled

Nov 18th, 2022
933
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. using System.Linq;
  2. using System.Drawing;
  3. using System.Net.Sockets;
  4. using static RoutePlanning.PointExtensions;
  5.  
  6. namespace RoutePlanning
  7. {
  8.     public static class PathFinderTask
  9.     {
  10.         public static int[] FindBestCheckpointsOrder(Point[] checkpoints)
  11.         {
  12.             var bestPath = MakeTrivialPath(checkpoints.Length);
  13.             var bestPathLength = checkpoints.GetPathLength(bestPath);
  14.             var startPath = new int[checkpoints.Length];
  15.             startPath[0] = 0;
  16.             FindBestPath(checkpoints, (int[])startPath.Clone(), 1, bestPath, bestPathLength, 0);
  17.  
  18.             return bestPath;
  19.         }
  20.  
  21.         private static int[] MakeTrivialPath(int size)
  22.         {
  23.             var bestOrder = new int[size];
  24.             for (var i = 0; i < bestOrder.Length; i++)
  25.                 bestOrder[i] = i;
  26.             return bestOrder;
  27.         }
  28.  
  29.         private static double FindBestPath(Point[] checkpoints, int[] currentPath, int position, int[] minPath,
  30.             double minLengthPath, double lastLengthPath)
  31.         {
  32.             var currentPathLength = UpdateLength(checkpoints, currentPath, position, lastLengthPath);
  33.  
  34.             if (currentPathLength > minLengthPath)
  35.                 return minLengthPath;
  36.  
  37.             if (currentPathLength <= minLengthPath && position == currentPath.Length)
  38.             {
  39.                 currentPath.CopyTo(minPath, 0);
  40.                 return currentPathLength;
  41.             }
  42.  
  43.             for (var i = 1; i < currentPath.Length; i++)
  44.             {
  45.                 if (currentPath.Contains(i))
  46.                     continue;
  47.                 var saveCheckpoint = currentPath[position];
  48.                 currentPath[position] = i;
  49.                 minLengthPath = FindBestPath(checkpoints, currentPath, position + 1, minPath, minLengthPath,
  50.                     currentPathLength);
  51.                 currentPath[position] = saveCheckpoint;
  52.             }
  53.  
  54.             return minLengthPath;
  55.         }
  56.  
  57.         private static double UpdateLength(Point[] checkpoints, int[] currentPath, int position, double lastLengthPath)
  58.         {
  59.             return position != 1
  60.                 ? lastLengthPath + checkpoints[currentPath[position - 2]]
  61.                     .DistanceTo(checkpoints[currentPath[position - 1]])
  62.                 : lastLengthPath;
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement