Skip to content
Advertisement

Why do arrays in recursive function permanently change when array is recursively called? (Java) [closed]

So the goal of this code is to recursively move through a 2d array with frogs on certain cells. A frog can jump over another frog and delete it. This code is supposed to see how many different ways you can do that to get it to one frog. But after one path is found, the original array is changed and it still only has a single frog from the previous path. How do I change this so that the original array isn’t affected?

JavaScript

x

Advertisement

Answer

You have to explicitly make a copy of the array and store it.

For a two-dimensional array, this means you need an entire loop to copy the array:

JavaScript

As for why, remember that objects are arrays and study https://stackoverflow.com/a/40523/869736.

Advertisement