java - StackOverflow error while using recursion -
this question has answer here:
- bfs arithmetic operations 3 answers
i trying number (n) (m) , me algorithm makes sense yet crashes stackoverflow error. help? here's code:
private static int solve(int n, int m, int steps) { if (n > m || n <= 0) { //--steps; return 0; } else if (n == m) return steps; return math.min(solve(n * 2, m, steps++), solve(n - 1, m, steps++)); }
update::: code solve problem elegantly
private static int solve(int n, int m) { int steps = 0; int cur = n; arraylist<integer> arr = new arraylist<>(); //setting list of best minimum track. arr.add(m); (int = 0; !arr.contains(1); ++i) arr.add((int) math.round((double) arr.get(i) / 2)); //aligning number n track , applying best track.(imagine stair of steps , have reach top of it, you'll align 1 of steps , voooom :) ) while (cur != m) { if (arr.contains(cur)) cur *= 2; else cur--; steps++; } return steps; }
this algorithm traverses all possible paths in tree 1 branch represents multiplication , 1 decrement 1. problem "all", since there path this:
n = 2 m = 5 branch selection *2 -1 -1 *2 -1 -1 *2 ... n after branch 4 3 2 4 3 2 4 ...
which never abort.
and doubt algorithm will, though makes perfect sense , apart obvious issue stackoverflowexception
solve problem in cases. guess, problem find minimum-number of multiplications , decrements required transform n
m
. algorithm cases return 0.
a correct solution require bfs, unlike (incorrect) dfs-implementation solution uses. there additional set
visited nodes required implement correct dfs-traversal, invalid solutions have marked explicitly. bfs on other hand aswell require store depth @ value visited:
public int solve(int n , int m , int step , map<integer , integer> visitedat){ //no valid solution if(n > m * 2 || n <= 0) return -1; //a solution found @ step if(n == m) return step; //the node visited less steps if(visitedat.containskey(n) && visitedat.get(n) <= step) return -1; //store visited value , step @ visited visitedat.put(n , step); //calculate number of steps required reach m if next step //either decrement or multiply 2 int dec = solve(n - 1 , m , step + 1 , visitedat); int mul = solve(n * 2 , m , step + 1 , visitedat); if(dec == -1)//no possibility reach m decrementing n return mul; else if(mul == -1)//cant reach m multiplying n 2 return dec; else //both lead valid solutions, find minimum number of steps return math.min(dec , mul); }
though solution isn't elegant implementation of bfs-algorithm. fulfills requirement of being recursive.
Comments
Post a Comment