我需要用递归法找到最便宜的路。这条路从点1开始,它需要穿过所有其他点(2,3,4,5),然后回到点1。每个点之间的行程成本在一个二维数组(map)中。
╔═══════════════════════╗
║ 1|2|3|4|5|(points) ║
║ 1--0 1 3 4 2 ║
║ 2--1 0 4 2 6 ║
║ 3--3 4 0 7 1 ║
║ 4--4 2 7 0 7 ║
║ 5--2 6 1 7 0 ║
║ (points) ║
╚═══════════════════════╝
这意味着,例如从点1到点5有2个“钱”成本,从点5到点4成本是7每次你在地图上切换“方向”。我认为尝试应该等于25(4+(一)
void FindingRoad(int[][] map, int[] pointsOrder, ref int tripCost, ref int attempts)
{
if (attempts == 0)
{
return;
}
int tempCost = 0;
int[] tempPointsOrder = new int[5];
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
}
}
if (tempCost<tripCost)
{
tripCost = tempCost;
pointsOrder = tempPointsOrder;
}
attempts--;
FindingRoad(map,pointsOrder,ref tripCost,attempts);
}
预期道路(点顺序)输出应为1、5(2)、3(1)、2(4)、4(2)、1(4),成本=13
关于
for
循环的外观有什么建议吗? 最佳答案
主要有三个功能第1和第2步创建所有可能的道路,第3步计算其成本。希望能有所帮助
static void AllRoads(int[] a, int size, int n, RoadContainer VisiKeliai, int[][]map)
{
// if size becomes 1 then prints the obtained
// permutation
if (size == 1)
printArr(a, n, VisiKeliai,map);
for (int i = 0; i < size; i++)
{
AllRoads(a, size - 1, n, VisiKeliai,map);
// if size is odd, swap first and last
// element
if (size % 2 == 1)
{
int temp = a[0];
a[0] = a[size - 1];
a[size - 1] = temp;
}
// If size is even, swap ith and last
// element
else
{
int temp = a[i];
a[i] = a[size - 1];
a[size - 1] = temp;
}
}
}
static void printArr(int[] a, int n, RoadContainer VisiKeliai, int[][]map)
{
string s = "0";
// Console.WriteLine("dassaddsasdaasdas" + a.Length);
for (int i = 0; i < n; i++)
{
// Console.Write(a[i] + " ");
s += Convert.ToString(a[i]);
}
s = s.Insert(s.Length, "0");
Road r = new Road(s);
CalculatingPrice(r, map);
VisiKeliai.AddRoad(r);
//Console.WriteLine(s);
}
public static void CalculatingPrice(Road Kelias, int[][] map)
{
// 021430 Road im checking
Console.WriteLine("Kelias: " + Kelias.Path);
for (int i = 0; i < Kelias.Path.Length - 1; i++)
{
int nextI = i + 1;
for (int j = 0; j < 5; j++)
{
for (int m = 0; m < 5; m++)
{
string a = Convert.ToString(m);
string aaa = Convert.ToString(Kelias.Path[i]);
string b = Convert.ToString(j);
string bbb = Convert.ToString(Kelias.Path[nextI]);
if (a == aaa && b == bbb)
{
Console.WriteLine(a + "--" + aaa + "---" + b + "----" + bbb + "-------------" + map[j][m]);
Kelias.Cost += map[j][m];
}
}
}
}
}