c# - 用递归找到最便宜的路
问题描述
我需要使用递归找到最便宜的道路。
道路从点 1 开始,需要经过所有其他点(2、3、4、5)并返回到点 1。每个点之间的行程成本在一个二维数组(地图)中。
╔═══════════════════════╗
║ 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! + 1)
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
循环的外观有什么建议吗?
解决方案
Traveling Saleman Problem是一个已知为NP-hard的优化问题,这意味着它不太可能承认有效的最优算法。话虽如此,可以使用动态编程在指数运行时范围内解决它。这种算法可以在这里找到,或者(在最近的出版物中)在这里。
推荐阅读
- javascript - 冻结浏览器 DOM 状态以检查基于事件的元素?
- batch-file - 如何在 .nsh 或 nsis 安装程序中运行或执行 .bat 文件(就像我们使用 cmd.exe 手动运行 .bat 文件一样)?
- java - 如何从自动生成的标签中访问值?
- axios - Axios Vue Js:如何获取此对象的值以显示在 api get request url
- python - 在 pytorch 或 huggingface/transformer 标签的代码中哪里被“重命名”为标签?
- android - com.example.androiddata.databinding.FragmentDetailBindingImpl.executeBindings(FragmentDetailBindingImpl.java:147)
- jquery - JSP 上的 JQUERY AJAX 和 SELECT ELEMENT
- c++ - 如何在 Visual Studio 2015 中使用 C++ 语言?
- android - 如何恢复意外删除的 Flutter 代码文件?
- nlp - 在 spacy 中使用 glove.6B.100d.txt 嵌入得到零 lex.rank