0

Given this smaller scale of what I am trying to achieve in Java:

int[][] arr = new int[2][2]{ 
    { 1, 0 },
    { 0, 1 }
};
int[][] path = null;

Queue<int[][]> q = new LinkedList<int[][]>();
q.add(arr);

while(q.size() != 0) {
    path = q.poll();    // pop the queue

    for (int i=0; i<2; i++) {
        for (int j=0; j<2; j++) {
            if (path[i][j] == 0) {
                path[i][j] = 1;
                q.add(path);
                path[i][j] = 0;
            }
        }
    }
}

I had traced the contents of q for each iteration inside the while and for loops via NetBeans. They are, however, of the same values.

I was expecting this on the end for the first for-loop execution:

{ {1 , 1} , {0 , 1} } and { {1 , 0} , {1 , 1} }

But instead, they are:

{ {1 , 0} , {0 , 1} } and { {1 , 0} , {0 , 1} }

which is the last value of the array path, as the 1st execution of the nested for-loop has ended.

What should I do so that the one that I am pushing to q is not a reference to the path array?

Kevin Lloyd Bernal
  • 355
  • 3
  • 8
  • 24

1 Answers1

1

Try to add the copy of the path array.

for (int i=0; i<2; i++) {
    for (int j=0; j<2; j++) {
        if (path[i][j] == 0) {
            path[i][j] = 1;

            // here
            int[][] copy = new int[2][2];
            for(int k=0; k<2; k++) {
                copy[k] = path[k].clone();
            }

            q.add(copy);

            path[i][j] = 0; // now, this does not affect the added element
        }
    }
}

EDIT: You cannot clone the path variable since there are references on the first level of the array.

Jindra Helcl
  • 3,457
  • 1
  • 20
  • 26
  • Sorry, still not working.. in NetBeans debugger, the references of the values are different.. (#1356 and #1357 in my case). But the values are the same.. – Kevin Lloyd Bernal Dec 05 '13 at 13:16
  • Sorry, there was I mistake I made - clone() does only a shallow copy of an object, so if you clone a two-dimensional array, it'll do no good. It works though for cloning the second dimension (because it contains only primitive types) – Jindra Helcl Dec 05 '13 at 13:26
  • Ohhh.. It works! Thanks man! I was reading these ones when you edited your answer: stackoverflow.com/questions/4892992/array-seems-to-be-getting-passed-by-reference-in-java-how-is-this-possible http://stackoverflow.com/questions/1564832/how-do-i-do-a-deep-copy-of-a-2d-array-in-java It works now. Thanks again! – Kevin Lloyd Bernal Dec 05 '13 at 13:30