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

时间:2018-09-06 16:54:44

标签: 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 is not visited then
                mark u visited
                push u onto S
我在此链接上找到的

http://www.csl.mtu.edu/cs2321/www/newLectures/26_Depth_First_Search.html

但是,当我实现它并在多个测试示例上对其进行测试时,它不会产生预期的结果,即顶点未按预期的顺序打印。这是我的代码:

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;
                }
            }
        }
    }

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

0 个答案:

没有答案