Counting the number of edges traversed in a Breadth First Search?

人走茶凉 提交于 2019-12-06 13:42:30

In your Vertex class, create a Vertex cameFrom field which you set to point to the Vertex you came from when that node was visited. You could even replace your boolean visited field with this (if it is null the Vertex hasn't been visited yet).

Then, when you find the Vertex y just follow the pointers back to Vertex x counting how many steps it takes as you go.

If you don't want to change your Vertex class, then just keep a Map<Vertex,Vertex> during your search which stores the mappings from the vertex you're visiting to the vertex you came from. When you get to the end you can follow the path to the beginning in the same way.


Something along these lines perhaps:

    public int distance(Vertex x, Vertex y){
        Queue<Vertex> search = new LinkedList<Vertex>();
        search.add(x);
        while(!search.isEmpty()){
            Vertex t = search.poll();
            if(t == y){
                return pathLength( t );
            }
            for(Vertex n: t.neighbours){
                if(n.cameFrom == null || n != x){
                    n.cameFrom = t;
                    search.add(n);
                }

            }
            System.out.println(search + " " + t);
        }
        return -1;  
    }

    public int pathLength( Vertex v )
    {
       int path = 0;

       while ( v.cameFrom != null )
       {
         v = v.cameFrom;
         path++;
       }

       return path;
    }

In this example, the number of edges is simply the size of the search. queue.

EDIT:

One possible solution is to do it layer by layer. Lets say you asked for the distance between Vertex A, F

and the Graph looks like:

A
|\
B C
|
D
|\
E F

First calculate the distance between A and B,C (which is easy because B and C are immediate neighbors of A. Then calculate the distance between A and D (which is easy because D is an immediate neighbor of B, then A and E, F. Store the distance in the A vertex node. Now after you've run the BFS and determined the search result, you can simply ask for the distance. Look at this visual diagram.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!