コード例 #1
0
    int Dijkstra(Node source, Node target)
    {
        if (start == null || target == null)
        {
            return(0);
        }
        if (start.connectedEdges.Count == 0)
        {
            return(0);
        }



        foreach (var node in graph.GraphNodes)
        {
            node.pathLength     = int.MaxValue;
            node.parentNode     = null;
            node.hasBeenVisited = false;
        }
        start.pathLength = 0;


        while (graph.GetUnvisitedNodes().Count > 0)
        {
            Node top = graph.GetUnvisitedNodes().OrderBy(y => y.pathLength).First();
            if (top.label == target.label)
            {
                Debug.Log("found Target" + top.pathLength);
                return(graph.CalcPathLength(target, 0));
            }
            top.hasBeenVisited = true;

            foreach (var edge in top.connectedEdges)
            {
                Node neighbour = edge.GetFarNode();
                if (!neighbour.hasBeenVisited)
                {
                    int distance = top.pathLength + edge.GetCost();                      // cost
                    if (distance < neighbour.pathLength)
                    {
                        Debug.Log(top.pathLength);
                        neighbour.pathLength = distance;
                        neighbour.parentNode = top;
                    }
                }
            }
        }
        return(0);
    }