【问题标题】:How to compute distance to all other vertices in Graph using BFS?如何使用 BFS 计算到 Graph 中所有其他顶点的距离?
【发布时间】:2020-05-10 19:02:27
【问题描述】:

如何使用 BFS 搜索计算从起始顶点到所有其他顶点的距离? 如果没有到顶点的路径,则距离应报告为 -1。 我有一个生成 Graph 的类和一个我已经实现 BFS 搜索的方法 distance(int start),但我不知道如何计算距离并以合适的数据结构返回它。

预期输出:


graph.distance(0);
>>> Distance from vertex 0 to 1 is 1
>>> Distance from vertex 0 to 2 is 1
>>> Distance from vertex 0 to 3 is 2
>>> Distance from vertex 0 to 4 is 2
>>> Distance from vertex 0 to 5 is 3
import java.util.*;
import static java.lang.System.out;
import java.util.concurrent.ThreadLocalRandom; 


public class Graph {
    int _vertices;
    ArrayList<ArrayList<Integer>> adj_list;

    private void addEdge(int u, int v) {
        adj_list.get(u).add(v);
        adj_list.get(v).add(u); 
        //out.println(adj_list);
    }

    /*
     * loop through all pairs of vertices u, v and decide, 
     * randomly with probability p, whether the edge (u, v) 
     * is in the graph.
     */

    Graph(int vertices, double prob){
        _vertices = vertices;
        adj_list = new ArrayList<ArrayList<Integer>>(vertices);
        for (int u = 0; u < vertices; u++) {
            //System.out.println(i);
            adj_list.add(new ArrayList<Integer>());
        }
        for (int v = 0; v < vertices; v++) {
            for(int u = 0; u < vertices; u++) {
                double random = ThreadLocalRandom.current().nextDouble(0, 1);
                if (random > prob) {
                    //System.out.println(checkElem(adj_list, v));
                    if (checkElem(adj_list, v, u) == false && u != v){
                        addEdge(v, u);
                    }
                }
            }
        }
    }

    public void printGraph() { 

        for (int i = 0; i < adj_list.size(); i++) { 
            System.out.println("\nAdjacency list of vertex " + i); 
            for (int j = 0; j < adj_list.get(i).size(); j++) { 
                System.out.print(" -> "+adj_list.get(i).get(j)); 
            } 
            System.out.println(); 
        } 
    }

    /*
     * @param vert: A vertex in the graph
     */
    public void printVertex(int vert) {
        System.out.print(" -> "+adj_list.get(vert)); 
    }

    /*
     * @param arr: list of list that represents graph
     * @param vertex: a vertex in the graph
     * @param node: node to be checked in vertex
     */
    private boolean checkElem(ArrayList<ArrayList<Integer>> arr, int vertex, int node) {
        ArrayList<Integer> temp = arr.get(vertex);
        if(temp.contains(node)){
            return true;
        } else {
            return false;
        }
    }

    /*
     * @param start: A vertex to start the search from in the graph
     */
    public void distance(int start) {
        boolean visited[] = new boolean[_vertices];
        ArrayList<Integer> queue = new ArrayList<Integer>();

        visited[start] = true; 
        queue.add(start); 


        while (queue.size() != 0) { 
            //out.println(queue);

            // Dequeue a vertex from queue and print it             
            start = queue.remove(0);

            // Get all adjacent vertices of the dequeued vertex s 
            // If a adjacent has not been visited, then mark it 
            // visited and enqueue it 
            ArrayList<Integer> temp = adj_list.get(start);
            Iterator<Integer> i = temp.listIterator();

            //out.println("Vertex: " + start +" Dist: " + edgeDist);
            while (i.hasNext()) { 
                out.println(start);
                int n = i.next(); 


                if (!visited[n]) {  
                    visited[n] = true; 
                    queue.add(n);                 
                } 
            }   
        }
    }

    public static void main(String[] args) {
        Graph graph = new Graph(5, 0.5);
        graph.distance(0);
    }   
}

【问题讨论】:

    标签: java graph breadth-first-search


    【解决方案1】:

    计算从源到所有邻接的距离

    更新您的代码以使用isEmpty(),因为它是固定时间,不要使用size()==0 , 使用Queue添加邻接顶点

     public int distance(int vertex) {
                boolean visited[] = new boolean[_vertices];
                Queue<Integer> queue = new ArrayDeque<>();
    
                visited[vertex] = true;
                queue.add(vertex);
    
                int distance = 0;
    
                while (!queue.isEmpty()) {
                    int v = queue.poll();
    
                    List<Integer> adj = adj_list.get(v);
                    distance++;
                    for (Integer w : adj) {
                        if (!visited[w]) {
                            System.out.println("Distance from vertex: " + vertex + " to: " + w +" is " + distance);
                            visited[w] = true;
                            queue.add(w);
                        }
                    }
                }
                return distance == 0 ? -1 : distance;
            }
    

    【讨论】:

    • 感谢您就问题的时间复杂度提供意见!如果我可能会问,System.out.println(w); 打印出顶点的边 vdistance 在搜索所有节点后返回距离,我没有看到它返回给定顶点的所有顶点的距离?跨度>
    • 我添加了预期的输出来澄清问题
    • 它几乎可以工作了!我注意到,如果到顶点的距离大于 1,则起始顶点将更改为相邻顶点,然后计算从相邻顶点到该顶点的距离。前任。 V=5 如果顶点 0 具有节点 1、2、3,则输出为 Distance from vertex: 0 to: nodes is 1,但对于不是顶点 0 的节点的顶点 4,则输出类似于 Distance from vertex: 1 to: 4 is 2。你明白还是我应该澄清一下?
    • 我将 v 更改为 vertex 打印语句中的源
    • 感谢您抽出宝贵时间,它按预期完美运行!
    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2015-11-12
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    相关资源
    最近更新 更多