Exemplo n.º 1
0
        static void Dijkstra(List <Node> nodelist, Node root)
        {
            //set all distances from root
            List <Node> Nodelist = new List <Node>();

            foreach (Node node in nodelist)
            {
                Nodelist.Add(node);
                if (!root.Distances.ContainsKey(node))
                {
                    root.Distances[node] = int.MaxValue;
                    node.bestpath[root]  = null;
                }
            }

            root.Distances[root] = 0; //forces first selectednode to be the root


            while (Nodelist.Count > 0)
            {
                Node selectednode = root;
                selectednode = selectednode.MinDistanceToNode(Nodelist); // selects node with minimal costs (I am not using queue because you don't know all the costs so you don't know the order)
                Console.WriteLine(selectednode.Letter);                  // prints node so you can see the path it takes
                Nodelist.Remove(selectednode);                           // removes the selected node from lists

                foreach (Node neighbour in selectednode.Adjacentnodes)
                {
                    // Normally you would calculate the costs between neighbour nodes here. But I calculated those beforehand
                    int alt = root.Distances[selectednode] + selectednode.Distances[neighbour];

                    //for not going negative if value gets over int cap
                    if (root.Distances[selectednode] == int.MaxValue || selectednode.Distances[neighbour] == int.MaxValue)
                    {
                        alt = int.MaxValue;
                    }

                    // replaces distance if found a shorter path
                    else if (alt < root.Distances[neighbour])
                    {
                        root.Distances[neighbour] = alt;
                        root.bestpath[neighbour]  = selectednode;
                    }
                }
            }
        }