【问题标题】:Depth first search and Breadth first search between two nodes in graph图中两个节点之间的深度优先搜索和广度优先搜索
【发布时间】:2013-11-25 01:57:32
【问题描述】:

我有一个无向连通图。我已经使用一个二维数组的邻接矩阵来实现它。

据我了解,DFS 在兄弟节点之前访问子节点。 BFS 在孩子之前拜访兄弟姐妹。

我是这样实现这两个的:

    public void DFT(int firstVertex) {
    connectedVertices = 0;
    int v;
    Stack<Integer> stack = new Stack<Integer>();
    for (int i = 0; i < numVertices; i++) {
        if(vertex[i] != null){
            vertex[i].setPushed(false);
        }
    }
    stack.push(firstVertex);
    connectedVertices++;
    vertex[firstVertex].setPushed(true);

    while(!stack.isEmpty()){
        v = stack.pop();
        vertex[v].visit();
        for (int i = 0; i < numVertices; i++) {
            if(adj[v][i] != 0 && !vertex[i].getPushed()){
                stack.push(i);
                connectedVertices++;
                vertex[i].setPushed(true);
            }   
        }
    }

}

public void BFT(int firstVertex) {
    connectedVertices = 0;
    int v;
    Queue<Integer> queue = new LinkedList<Integer>();
    for (int i = 0; i < numVertices; i++) {
        if(vertex[i] != null){
            vertex[i].setPushed(false);
        }
    }
    queue.add(firstVertex);
    connectedVertices++;
    vertex[firstVertex].setPushed(true);

    while(!queue.isEmpty()){
        v = queue.remove();
        vertex[v].visit();
        for (int i = 0; i < numVertices; i++) {
            if(adj[v][i] != 0 && !vertex[i].getPushed()){
                queue.add(i);
                connectedVertices++;
                vertex[i].setPushed(true);
            }   
        }
    }

}

因为这些方法只接受一个参数,即起始顶点。如果我被要求将 DFS 和 BFS 从一个节点提供给另一个节点怎么办?这是一个连接无向图的简单示例。

如果要求我执行从 D 到 E 的 DFS,是 D、C、A、E 还是 D、E。我认为 DFS 和 BFS 必须访问每个节点,在这种情况下 B 无法访问。我不知道我应该如何改变我目前的方法来满足这些要求。

【问题讨论】:

    标签: java data-structures graph depth-first-search breadth-first-search


    【解决方案1】:

    我不确定你先访问 C 还是 E 是否真的重要。他们都是D的孩子,对吧?它是特定于实现的行为,DFS 没有定义您首先访问哪个孩子。

    在 DFS 中,如果您先选择孩子 C,那么您应该先访问 A,然后再访问 E。

    在 BFS 中,您应该先访问过 E 和 C,然后再访问 A 或 B。

    【讨论】:

    • 啊,好吧,但是如果我被要求从一个顶点到另一个顶点执行 dfs 或 bfs,我是否一击中第二个顶点就完成了?还是我必须继续访问剩余的顶点?在上面的例子中,无论我先访问 C 还是 E,如果最终顶点是 E,我都无法到达 B。DFS/BFS 是否要求您访问连接组件中的每个顶点?
    • @Infodayne 如果您被要求从 D 到 E 搜索(DFS 或 BFS),那么您应该在到达 E 后立即停止;您无需继续。理论上,如果靠近起点,BFS会先找到顶点;其中,DFS 会先找到离起点较远的顶点。
    猜你喜欢
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 2012-05-23
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多