i'm trying to make a recursive method to check if the last number (always 0) in an integer array (with all > 0 integers) is reachable by increasing (or decreasing) the index of the array with the value of the array element of the current index, while staying within the bounds of the array.
example:
say we have the following array, and the 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 with this is that it will only work with solveable cases, all other cases will result in a stackoverflow exception.
how would i be able to solve this problem WITHOUT using global variables to store previous results?
EDIT:
I can only use the parameters: (int index, int[] arr)