Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
}
like image 584
Mohammed Mohammed Avatar asked Mar 22 '14 16:03

Mohammed Mohammed


2 Answers

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

like image 140
Hakan Serce Avatar answered Oct 06 '22 00:10

Hakan Serce


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

like image 42
Sandeepraj Tandon Avatar answered Oct 06 '22 02:10

Sandeepraj Tandon