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


can me how count visited levels of graph using breadth first search in java?

here method, have start node (str) , end node (goal), when loop reach goal node should stopped.

what want counting levels start node 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;        }                     (int j = 0; j < nverts; j++) {         vertexlist[j].wasvisited = false;     } } 

you can use 1 of following approaches track current level:

  1. use 2 queues instead of one: currentlevelqueue , nextlevelqueue

  2. use 1 queue track nodes 1 track associated level

  3. use wrapper class includes level field , store instances of class in queue


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -