如何使用BFS计算到图形中所有其他顶点的距离?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用BFS计算到图形中所有其他顶点的距离?相关的知识,希望对你有一定的参考价值。

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

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

答案

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

更新您的代码以使用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);

                for (Integer w : adj) 
                    System.out.println(w);

                    if (!visited[w]) 
                        visited[w] = true;
                        queue.add(w);
                        distance++;
                    
                
            
            return distance == 0 ? -1 : distance;
        

以上是关于如何使用BFS计算到图形中所有其他顶点的距离?的主要内容,如果未能解决你的问题,请参考以下文章

如何在bfs java中获取两个顶点之间的所有边

顶点法线的图形问题

HDU 5876 Sparse Graph(补图上BFS)

如何计算缩小到一个图形中的顶点数?

在图数据结构中,我们如何使用中间节点来计算任何其他两个节点的距离?

深度优先搜索(DFS)和广度优先搜索(BFS)