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;
}
}
You can use one of the following approaches to track the current level:
Use two queues instead of one: currentLevelQueue and nextLevelQueue
Use one queue to track the nodes another one to track the associated level
Use a wrapper class that includes a level field and store instances of this class in the queue
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With