利用栈实现DFS

public static void DepthFirstSearch(Graph graph, Vertex sourceVertex)
        {
            foreach(Vertex vertex in graph.Vertices)    //初始化每一个结点
            { 
                vertex.visited = false;
                vertex.Parent = null;
                vertex.Distance = 0;    //设置初始距离为0
            }

            Stack> dStact = new Stack>();
            sourceVertex.visited = true;
            dStact.Push(sourceVertex);   //栈中放入初始结点
            
            while(dStact.Count > 0)
            {
                Vertex curVertex = dStact.Pop();   //栈首出栈

                foreach(Vertex vertices in graph.GetAdjacentVertices(sourceVertex))   //扫描栈首结点的每一个邻接结点
                {
                    if (!vertices.visited)
                    {
                        vertices.visited = true;
                        vertices.Distance = curVertex.Distance + graph.GetEdgeWeight(curVertex, vertices);  
                        vertices.Parent = curVertex;   //保留父结点用以打印路径
                        dStact.Push(vertices);   //入栈
                    }
                }
            }
        }

 

你可能感兴趣的:(数据结构与算法)