简体   繁体   English

java 中图的连通性

[英]Connectivity of a graph in java

I've implemented a BFS algorithm from my textbook and I am trying to modify it to throw an exception when it discovers a non-connected graph.我已经从我的教科书中实现了一个 BFS 算法,并且我正在尝试对其进行修改以在发现非连接图时抛出异常。 My BFS using an array of boolean to store if a node has been reached or not.我的 BFS 使用 boolean 数组来存储是否已到达节点。 After running the BFS from the root node I thought I could iterate through the array and check if each node was reached.从根节点运行 BFS 后,我想我可以遍历数组并检查是否到达每个节点。 My code throws an exception every time and I cannot figure out why.我的代码每次都会抛出异常,我不知道为什么。 Any guidance would be appreciated thanks!任何指导将不胜感激谢谢!

Code:代码:

private int bfs(Graph G, int s) {
    int d = 0;
    Queue<Integer> q = new Queue<>();
    int distTo[] = new int[G.V()], max = 0;
    boolean[] marked = new boolean[G.V()];
    int[] edgeTo = new int[G.V()];
    for(int v = 0; v < G.V(); v++) {
        distTo[s] = Integer.MAX_VALUE;
        marked[s] = true;
        distTo[s] = 0;
        q.enqueue(s);
    }
    
    while(!q.isEmpty()) {
        d = q.dequeue();
        for(int w : G.adj(d)) {
            if(!marked[w]) {
                edgeTo[w] = d;
                distTo[w] = distTo[d] + 1;
                marked[w] = true;
                q.enqueue(w);
            }
        }
        for(boolean x : marked) {
            if(x == false) throw new RuntimeException("not a connected graph.");
        }
    }
    return d;
}

You check for connectivity after processing each vertex.在处理每个顶点后检查连通性。 Only in the simplest graphs will the test succeed after the first vertex.只有在最简单的图中,第一个顶点之后的测试才会成功。

Instead you should seed the queue with one vertex and move the for loop testing for connectivity out of the while loop.相反,您应该使用一个顶点为队列播种,并将用于连接性的 for 循环测试移出 while 循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM