Graph DFS in Java giving stack overflow error on large input -


this homework problem- given undirected graph, if 2-colorable, color it, , if not, output odd-length loop within it. method goes through, coloring goes, , if finds loop pops stack , outputs loop. works fine small input, on large input gives stack overflow error. there can not overflow large input?

p.s. know should using getter , setter methods variables in node. children list of nodes edge given node.

public static boolean isoddloop(node current){     for(int x=0; x<current.children.size(); x++){         node next = current.children.get(x);         if(next.color==0){ //i.e. unvisited             next.color=3-current.color; //colors 1 , 2, sets opposite             if(isoddloop(next)){                 system.out.println(current.number + ": " + current.color);                 return true;             }            }         if(next.color==current.color){             system.out.println(next.number + ": " + next.color);             system.out.println(current.number + ": " + current.color);             return true;         }     }     return false; } 

as comment above says, increasing memory allocated jvm stack alleviate problem. see post here on java stack overflow error - how increase stack size in eclipse?

a better solution in opinion switch bfs instead of dfs. using bfs valid solution 2-coloring problem. furthermore, bfs can done queue , no recursion. then, you'd have far smaller stack , limited heap size instead. note since no longer have stack keep track of parent node, you'll need add pointer parent node in node class , update go.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -