2

I am trying to write a 3x3 square-shift puzzle solver in Java. However, I'm stuck on the part where I shift the blocks around - I kept ending up with a bunch of new empty spaces with the algorithm I was using. After some testing I determined that it was because, in spite of my use of the clone() command, v's array is still being affected when I change "current". Does anyone know why this is and how I can fix it? I thought that after using clone, I could change the new array without affecting the old one.

    if (!rightwall)
    {
        int[][] current = v.state.clone();
        current[x][y] = current[x][y + 1];
        current[x][y + 1] = 0;
        State w = new State(current);
        w.distance = v.distance + 1;
        w.path = v;
        System.out.println("Right Shift:");
        w.print();
        q.insert(w);
    }

State is a class that represents a two-dimensional array along with some properties - the first part of the code for State is

public class State {
int[][] state = new int[3][3];
int distance = 0;
boolean known = false;
State path = null;
State(int[][] newstate){
    state = newstate.clone();
}

v is the state representing the current position. w would then be an "adjacent" position created after switching the empty space with the space next to it.

q is a queue.

勿绮语
  • 9,170
  • 1
  • 29
  • 37
Andrew Latham
  • 5,982
  • 14
  • 47
  • 87

1 Answers1

8

In your State class, you need to make sure that all properties are deep copied.

勿绮语
  • 9,170
  • 1
  • 29
  • 37
  • How do I do that? The code is public class State { int[][] state = new int[3][3]; int distance = 0; boolean known = false; State path = null; State(int[][] newstate){ state = newstate.clone(); } – Andrew Latham Nov 27 '11 at 17:55
  • you should actually create a new instance of the array in your constructor and then copy the array from source to destination – allthenutsandbolts Nov 27 '11 at 18:02
  • You just cloned the array of arrays. This means that you have a new outer array, holding references to the same inner arrays as the old outer array. You should also clone all the inner arrays. See http://stackoverflow.com/questions/5563157/how-to-deep-copy-2-dimensional-array-different-row-sizes – JB Nizet Nov 27 '11 at 18:03
  • Thanks! That totally fixed everything. – Andrew Latham Nov 27 '11 at 18:08