java - Graph Node doesnt loop through all neighbouring nodes? -
im having troubles graph assignment, i've run issue cant seem find.
system.out.println(plattegrond.getgraph().neighbours("een").tostring()); system.out.println(plattegrond.isroute("een", "drie", new hashset<string>()));
these lines of code print
[twee, drie, vier] false
so seems, "een" has "twee", "drie", , "vier" neighbours. isroute method returns false. method shown below.
public boolean isroute(string nodea, string nodeb, set<string> visited) { visited.add(nodea); if(nodea.equals(nodeb)) { homecoming true; } for(string neighbour : graph.neighbours(nodea)) { if(!visited.contains(neighbour)) { homecoming isroute(neighbour, nodeb, visited); } } homecoming false; }
i've traced steps debugger, , in enhanced loop, "drie" not come neighbour. "twee" , "four" will. same problem happens if seek find path "zes". when inquire "twee" neighbours are,
[een, vier, zes]
the isroute method 1 time again homecoming false when inquire find route "zes". 1 time again "zes" not come in loop neighbour. however, when inquire find route either "twee" or "four" homecoming true.
im lost on one.
there problem there... in have if statement return.. first neighbour twee , not in list visit twee , never go next iteration because of homecoming statement.
try using boolean variable , doing this:
boolean b = false; for(string neighbour : graph.neighbours(nodea)) { if(!visited.contains(neighbour)) { // statement can never alter b false 1 time becomes true // , create sure homecoming after checking whole set of neighbours b = b || isroute(neighbour, nodeb, visited); } } homecoming b;
this might not exact right solution @ to the lowest degree know problem... returning after first item , not iterating on neighbours.
java recursion graph
No comments:
Post a Comment