【问题标题】:BFS on graph vertices and edges as neighbors将图顶点和边作为邻居的 BFS
【发布时间】:2016-11-03 13:53:22
【问题描述】:

我有一个图数据结构,是我从这篇文章中复制而来的 - http://www.dreamincode.net/forums/topic/377473-graph-data-structure-tutorial/

我想在上面实现 BFS 算法。我不完全确定如何 - 我看到/阅读的大多数关于算法的文章都使用更简单的数据结构。该数据结构存储顶点的哈希映射,其字符串表示形式为键,然后还存储边的哈希映射,使用整数作为键。

这是我在尝试实现我发现的 BFS 示例时遇到的问题的示例 -

public void bfs(Vertex rootNode){

        Queue q = new LinkedList();
        q.add(rootNode);
        rootNode.visited=true;
        while(!q.isEmpty()){
            Vertex n = (Vertex)q.poll();
            System.out.print(n.toString() + " ");
            for(Vertex adj : n.getNeighbors()){ -- Here's my problem. Get neighbors doesn't                                                     return a list of verts, it returns a list of                                                   edges.
                if(!adj.visited){
                    adj.visited=true;
                    q.add(adj);
                }
            }
        }

    }

我是否需要调用 getNeighbors 然后遍历邻域中的每个唯一顶点?

谢谢。

【问题讨论】:

  • ...并且edge有一个方法getNeighbor()。

标签: java algorithm graph graph-algorithm


【解决方案1】:

您确实需要调用getNeighbors 并遍历每条边(因此是每个顶点)。

public void bfs(Vertex rootNode){

        Queue q = new LinkedList();
        q.add(rootNode);
        rootNode.visited=true;
        while(!q.isEmpty()){
            Vertex n = (Vertex)q.poll();
            System.out.print(n.toString() + " ");
            for(Edge edge : n.getNeighbors()){
                Vertex adj = edge.getNeighbor(n);
                if(!adj.visited){
                    adj.visited=true;
                    q.add(adj);
                }
            }
        }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多