java - breadth first search error -
public int bfs(int maxdepth){ //maxdepth = 3 works.. maxdepth = 4 gives me error int src = 0; int dest = 2; int nodes = arr[src].length - 1; boolean[] visited = new boolean[nodes + 1]; int i; int countdepth = 0; int countpaths = 0; int element; queue.add(src); while(!queue.isempty() || countdepth != maxdepth) { element = queue.remove(); = element; while(i <= nodes) { if(arr[element][i] > 0 && visited[i] == false) { queue.add(i); visited[i] = true; if(arr[i][element] > 0) //if has 2 directions visited[i] = false; if(element == dest || == dest) countpaths++; } i++; } countdepth++; } return countpaths; }
i'm trying go 'x' amount of levels deep while counting # of paths destination.
for reason keep getting error:
exception in thread "main" java.util.nosuchelementexception @ java.util.linkedlist.removefirst(unknown source) @ java.util.linkedlist.remove(unknown source) @ graph.bfs(graph.java:48)
i don't understand what's going on. seems work when go 3 levels deep when change 4, doesn't work.
change
while(!queue.isempty() || countdepth != maxdepth)
to
while(!queue.isempty() && countdepth != maxdepth)
each graph has maximal depth. seems, set maxdepth larger it's possible given graph , loop tries continue bfsing after handling possible nodes (i.e when queue empty)
update try provide answer second question posted in comments if given information not enough, so, try extrasens=) guess, going calculate paths of length=1
, of length=2..
length=givenmaxdepth|maxpossibledepth
. saw queue
data structure didn't see declaration - are using same queue function calls? if yes, should clear queue after each call (best place call queue.clear()
before return statement).
also, see using new visited array in each call , it's correct if using global visited should "clear" visited after each call - in other words fill false.
Comments
Post a Comment