Java 实现深度优先搜索伪代码的意外行为

Java 实现深度优先搜索伪代码的意外行为,java,graph,depth-first-search,Java,Graph,Depth First Search,我尝试使用以下伪代码实现深度优先迭代搜索: iterative DFS(Vertex v) mark v visited make an empty Stack S push all vertices adjacent to v onto S while S is not empty do Vertex w is pop off S for all Vertex u adjacent to w do if u

我尝试使用以下伪代码实现深度优先迭代搜索:

iterative DFS(Vertex v)
    mark v visited
    make an empty Stack S
    push all vertices adjacent to v onto S
    while S is not empty do
        Vertex w is pop off S
        for all Vertex u adjacent to w do
            if u is not visited then
                mark u visited
                push u onto S
我在这个链接上找到了:

但是,当我实现它并在多个测试示例上测试它时,它并没有产生预期的结果,即顶点没有按预期顺序打印。这是我的密码:

public void dfs(int start) {
        Stack<Integer> stack = new Stack<>();
        boolean[] visited = new boolean[E.length];
        stack.push(start);
        while(!stack.empty()) {
            Integer vertex = stack.pop();
            System.out.print(vertex + " ");
            for(Edge e: E[vertex]) {
                if(!visited[e.v]) {
                    stack.push(e.v);
                    visited[e.v] = true;
                }
            }
        }
    }
public void dfs(int start){
堆栈=新堆栈();
boolean[]访问=新的boolean[E.length];
堆栈推送(启动);
而(!stack.empty()){
整数顶点=stack.pop();
系统输出打印(顶点+“”);
对于(边e:e[顶点]){
如果(!已访问[e.v]){
叠加推压(e.v);
访问[e.v]=真实;
}
}
}
}

我在问是否有人可以帮助我实现伪代码,并帮助我理解我的错误。

你能给我们举一个输出不正确的简单图的例子吗?是的,一个例子是这个输入:顶点7、边9和连接顶点对:01、02、13、23、24、25、35、46、56、,预期的输出是:0 2 4 6 5 3 1,但我的代码打印了这个:0 2 5 6 4 3 1首先,两个输出都是有效的DFS运行-这取决于存储在
E[vertex]
上的边的顺序-在您的情况下(2,4)在之前(2,5)。注意2个小的变化:DFS,根据您在顶点上访问的伪代码标记,您标记了边。伪标记和推送,你推送和推送谢谢你的澄清。