我想找到到节点成本最低的路线。它为我找到了几条路线,但没有最低成本的路线。
我的类来存储有关节点的信息:
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 的成本最低的路线