C# 图表-找不到到到节点的最小路由
我想找到到节点的最小成本的路线。 它为我找到了多条路线,但没有成本最低的路线 用于存储节点信息的My类:C# 图表-找不到到到节点的最小路由,c#,graph,graph-traversal,C#,Graph,Graph Traversal,我想找到到节点的最小成本的路线。 它为我找到了多条路线,但没有成本最低的路线 用于存储节点信息的My类: public class Graph { //public int[][] childNodes; //public Graph(int[][] nodes) //{ // this.childNodes = nodes; //} public List<Node> nodes = new List<Node>(
public class Graph
{
//public int[][] childNodes;
//public Graph(int[][] nodes)
//{
// this.childNodes = nodes;
//}
public List<Node> nodes = new List<Node>();
}
public class Node
{
public Node(int node)
{
this.node = node;
}
public int node { get; set; }
public List<Tuple<int,int>> endNodes = new List<Tuple<int,int>>();
}
public class Routes
{
public int depth { get; set; }
public int cost { get; set; }
public List<string> nodes = new List<string>();
}
在元组中我有int,int-第一个int是结束节点,第二个int是到这个节点的路由成本
类来遍历图形:
public List<string> visited = new List<string>();
public List<Routes> routes = new List<Routes>();
public void dfs2(Node node, List<Routes> routes, Routes route, int depth)
{
depth++;
foreach (Tuple<int,int> childNode in g.nodes[node.node].endNodes)
{
string path = string.Format("{0}{1}", node.node, childNode.Item1);
string pathReverse = string.Format("{0}{1}", childNode.Item1, node.node);
// if (!visited.Contains(path)) // && !visited.Contains(pathReverse))
if(!route.nodes.Contains(path)) // && !route.nodes.Contains(pathReverse))
{
visited.Add(path);
if (childNode.Item1 == 6)
{
Routes newRoutes = new Routes();
newRoutes.depth = depth;
newRoutes.cost = route.cost + childNode.Item2;
newRoutes.nodes.AddRange(route.nodes);
newRoutes.nodes.Add(path);
routes.Add(newRoutes);
}
else
{
route.depth = depth;
route.cost += childNode.Item2; // 2;//childNode.
route.nodes.Add(path);
dfs2(g.nodes[childNode.Item1], routes, route, depth);
}
Debug.WriteLine("przeszedłem: " + path);
}
}
}
在我的示例中,我想找到到节点6的成本最低的路由如果没有一个简洁但完整的代码示例,很难提供一个好的答案。在你的问题中,我甚至没有看到任何可以使用的示例图形数据,更不用说清楚地描述发生了什么以及你希望发生什么了 也就是说,您可能对研究经典的路径查找算法及其相关内容感兴趣: 该算法的基本思想是,对于图中的每条边,您需要一个成本值,对于每个节点,您需要一种方法来估计到目的地的剩余成本。请注意,剩余成本估算可以设置为0,这将导致对所有路径进行呼吸优先搜索…速度较慢,但如果您的图形足够小,算法可以在有用的时间内完成,则仍然会生成正确的结果。如果你的数据有助于计算好的估计,那就更好了 该算法的工作原理是跟踪当前节点的成本,并选择一个当前成本加上相邻节点的成本加上从该节点到目的地的估计成本最小化的相邻节点。维护按节点总成本加上估计成本排序的节点列表,以便在每次迭代中始终可以选择成本最低的节点。如果并且当当前路径加估计变得比其他访问节点的路径加估计更昂贵时,该算法有效地回溯到该较便宜的节点并从那里继续 本质上,它是在探索图表,根据对剩余距离的合理猜测,寻找成本最低的路径。该算法的性能将取决于您如何实现该猜测