static void MakePermutations(Point[] checkpoints, int[] permutation, int position, double currentPathLength, List <int[]> result) { if (position == permutation.Length) { if (currentPathLength < minPathLength) { minPathLength = currentPathLength; } result.Add(permutation.ToArray()); return; } for (int i = 1; i < permutation.Length; i++) { var index = Array.IndexOf(permutation, i, 1, position - 1); if (index == -1) { permutation[position] = i; double addedPath = PointExtensions.DistanceTo(checkpoints[permutation[position]], checkpoints[permutation[position - 1]]); if (currentPathLength > minPathLength) { return; } MakePermutations(checkpoints, permutation, position + 1, currentPathLength + addedPath, result); } } }
public static int[] FindCheckpointsOrder(Point[] checkpoints) { var way = new int[checkpoints.Length]; way[0] = 0; var min = double.MaxValue; var minindex = 0; for (var i = 1; i < checkpoints.Length; i++) { for (var j = 1; j < checkpoints.Length; j++) { if (Array.IndexOf(way, j) != -1) { continue; } var dist = PointExtensions.DistanceTo(checkpoints[i - 1], checkpoints[j]); if (dist < min) { min = dist; minindex = j; } } way[i] = minindex; } return(way); }
static void ChoosingBestPath(int[] bestPath, int[] order, int position, Point[] checkpoints) { int iteration = 0; double orderLength = 0; if (iteration > 0) { orderLength += checkpoints[order[iteration - 1]].DistanceTo(checkpoints[order[iteration]]); } if (orderLength > Maximum) { return; } if (position == order.Length) { double currentLength = 0; for (var i = 0; i < position - 1; i++) { currentLength += PointExtensions.DistanceTo(checkpoints[order[i]], checkpoints[order[i + 1]]); } if (currentLength < Maximum) { Maximum = currentLength; for (var i = 0; i < order.Length; i++) { bestPath[i] = order[i]; } } return; } double length = 0; for (var i = 0; i < position - 1; i++) { length += PointExtensions.DistanceTo(checkpoints[order[i]], checkpoints[order[i + 1]]); } if (length > Maximum) { return; } for (var i = 1; i < order.Length; i++) { var index = Array.IndexOf(order, i, 1, position - 1); if (index != -1) { continue; } order[position] = i; ChoosingBestPath(bestPath, order, position + 1, checkpoints); } }
static void MakePermutation(int[] order, double size, int position, int[] bestOrder, Point[] checkpoints) { if (position == order.Length) { order.CopyTo(bestOrder, 0); return; } for (int i = 1; i < order.Length; i++) { if (Array.IndexOf(order, i, 0, position) != -1) { continue; } order[position] = i; var newSize = size + PointExtensions.DistanceTo(checkpoints[order[position - 1]], checkpoints[order[position]]); if (newSize < checkpoints.GetPathLength(bestOrder)) { MakePermutation(order, newSize, position + 1, bestOrder, checkpoints); } } }