Counting levels in Breadth First Search (Distance between start node and goal node)

自闭症网瘾萝莉.ら 提交于 2019-12-10 13:26:31

问题


Can anyone help me how to count the visited levels of a graph using Breadth First Search in Java?

Here is my method, I have start node (str) and end node (goal), when the loop reach the goal node it should be stopped.

What I want now is counting the levels from start node to end node.

public void bfs(String str,String goal) {
    int strInx = findIndex(str);
    vertexList[strInx].wasVisited = true;
    theQueue.insert(strInx);
    int v2;
    boolean bre = false;
    while (!theQueue.isEmpty()) {
        System.out.println(vertexList[theQueue.getFront()].label);
        int v1 = theQueue.remove();
        while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
            vertexList[v2].wasVisited = true;
            System.out.println("--V2--->"+vertexList[v2].label);
            theQueue.insert(v2);

            if(goal.equals(vertexList[v2].label)) {
                bre=true;
                break;
            }
        }
        if(bre) 
            break;   
    }                
    for (int j = 0; j < nVerts; j++) {
        vertexList[j].wasVisited = false;
    }
}

回答1:


You can use one of the following approaches to track the current level:

  1. Use two queues instead of one: currentLevelQueue and nextLevelQueue

  2. Use one queue to track the nodes another one to track the associated level

  3. Use a wrapper class that includes a level field and store instances of this class in the queue




回答2:


i had a similar requirement where i had to count the levels in a bfs algo. I did it by creating a of hashmap of levelMap>.. the integer is the level number... nodes is the list of nodes at the same level... this helped me find out when to go to the next level by incrementing the level counter...while doing bfs..

pseudo code:

    HashMap<Integer, ArrayList<Node>> levelMap = new HashMap<Integer, ArrayList<Node>>();

.... int currentLevelFromMap = getCurrLevelFromMap(levelMap, currentNode);

            currentLevel = currentLevelFromMap + 1;

            if (currentLevelNodeList.size() != 0) {
                levelMap.put(currentLevel, currentLevelNodeList);
            }

currentLevelNodesList is the list of the nodes from a particular iteration of algorithm



来源:https://stackoverflow.com/questions/22580149/counting-levels-in-breadth-first-search-distance-between-start-node-and-goal-no

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