So I have been banging my head over this seemingly insignificant issue. I don't necessarily know what to search for. I have scoured around for solutions. I need to make a copy of 2D array. The array consists of objects (a class I created call Cell), but the as soon as I make a copy I store that copy into a hash map (for possible reference later), then continue to modify the original array. The issue is that the modifications to the original also affect the copy now in the hash map. Essentially at the end of the day, my hash map will consist of many versions of the same grid. I have tried array.clone(), System.arraycopy(...), Arrays.copyof(), the traditional for loop copying scheme.... Finally I realized that I need what was called a deep copy, where you copy each data field of each object into a new object into the array copy....yeah, that didn't work either. Take a look:
static Cell[][] gridCopy;
...
Cell[][] grid = getGrid(file); //get grid from a file (this is Sudoku if you must know)
...
static boolean SolveSudoku(Cell grid[][])
{
// If there is no unassigned location, we are done
if (unassigned == null)
return true; // success!
int row = unassigned.row;
int col = unassigned.col;
ArrayList<Integer> domain = unassigned.domain;
// consider digits 1 to 9
for (int num = 0; num < domain.size(); num++)
{
//if looks promising
if (isSafe(grid, row, col, domain.get(num)))
{
//gridCopy = new Cell[N][N];
instance++;
// make tentative assignment
grid[row][col].value = domain.get(num);
//here is my attempt at a deep copy
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
gridCopy[i][j] = new Cell(grid[i][j].row, grid[i][j].col, grid[i][j].value, grid[i][j].domain);
states.put(instance, gridCopy); //save the current state in a map for reference if we backtrack
//as soon as I change things here in the original, the copy in the 'states' map also changes
updateSpecifiedDomains(grid, row, col, domain.get(num), true);
printGrid(grid, "Instance" + String.valueOf(instance));
// return, if success, yay!
if (SolveSudoku(grid, choice))
return true;
// failure, un-assign & try again
//int temp = grid[row][col].value;
grid = states.get(instance); //retain previous state
grid[row][col].value = UNASSIGNED;
/*updateSpecifiedDomains(grid, row, col, temp, false);
while (domain.contains(temp))
grid[row][col].domain.remove((Integer)temp);*/
//domain.remove((Integer)num);
}
}
count++;
instance--;
return false; // this triggers backtracking
}