arrays - c# recursive step method -
i'm trying make recursive method check if last number (always 0) in integer array (with > 0 integers) reachable increasing (or decreasing) index of array value of array element of current index, while staying within bounds of array.
example:
say have following array, , start index == 0:
int[] arr = {3, 6, 4, 1, 3, 4, 2, 5, 3, 0};
step 0 : index = 0, value = 3
step 1 : index = 3, value = 1
step 2 : index = 4, value = 3
step 3 : index = 7, value = 5
step 4 : index = 2, value = 4
step 5 : index = 6, value = 2
step 6 : index = 8, value = 3
step 7 : index = 5, value = 4
step 8 : index = 9, value = 0 -- end
my current code:
static bool solveable(int index, int[] arr) { if (arr[index] == 0) return true; if (index + arr[index] < arr.length) return solveable(index + arr[index], arr); if (index - arr[index] >= 0) return solveable(index - arr[index], arr); return false; }
the thing work solveable cases, other cases result in stackoverflow exception.
how able solve problem without using global variables store previous results?
edit:
i can use parameters: (int index, int[] arr)
you correct stack overflow unsolvable cases: recursive code behave dog chasing own tail until, until reaches stack limit.
fortunately, can break infinite recursion observing have @ n
steps reach end of array, if reach @ all. therefore, add third parameter indicate how many steps have taken already. if reach 0 before number of steps passes n
, have path; otherwise, don't have path.
static bool solveable(int index, int[] arr, int stepssofar) { if (arr[index] == 0) return true; if (stepssofar > arr.length) return false; ... // rest of code; pass stepssofar+1 down next level }
i can use 2 parameters included in code snippet
you can mark indexes have visited in arr
placing -1
them. in order preserve array's original state, store old value in local variable, , set arr
before returning:
static bool solveable(int index, int[] arr) { if (arr[index] == 0) return true; if (arr[index] == -1) return false; int oldarratindex = arr[index]; arr[index] = -1; try { ... // rest of code } { arr[index] = oldarratindex; } }
Comments
Post a Comment