示例#1
0
        static void Main(string[] args)
        {
            //Instance of our graph
            MyGraph <string> myGraph = new MyGraph <string>();

            //Create the graph
            CreateGraph(ref myGraph);

            Queue q = new Queue();

            Node <String> rootNode   = myGraph.NodeSet[2]; //Idaho
            Node <String> targetNode = myGraph.NodeSet[6]; //South Dakota

            q.Enqueue(rootNode);
            rootNode.Visited = true;
            while (q.Count != 0)
            {
                Node <String> element = (Node <String>)q.Dequeue();
                foreach (Edge <String> edge in element.MyEdges)
                {
                    if (edge.To.Equals(targetNode))
                    {
                        edge.To.Parent = edge.From;
                        q.Clear();
                        Node <String> returning  = edge.To;
                        Stack         printStack = new Stack();
                        while (!returning.Equals(rootNode))
                        {
                            printStack.Push(returning.Parent.MyEdges.Find(x => x.To.Equals(returning)));
                            returning = returning.Parent;
                        }
                        while (printStack.Count > 0)
                        {
                            Console.WriteLine(printStack.Pop());
                        }
                        break;
                    }

                    if (!edge.To.Visited)
                    {
                        q.Enqueue(edge.To);
                        edge.To.Visited = true;
                        edge.To.Parent  = edge.From;
                    }
                }
            }
        }