The variable puzzle is set to have the same initial value as the variable STORED, but is then changed through the solve method. The STORED variable is never used in any of the methods. If STORED is printed before the solve method it returns its initial 2D array, but in the if statement it prints out the new solved value of puzzle instead.
public class CA_Cindy {
public static boolean isSafe(int[][] board, int row, int col, int num)
{
int sqrt;
int boxRowStart;
int boxColStart;
for (int d = 0; d < board.length; d++)
{
if (board[row][d] == num)
return false;
}
for (int r = 0; r < board.length; r++)
{
if (board[r][col] == num)
return false;
}
sqrt = (int) Math.sqrt(board.length);
boxRowStart = row - row % sqrt;
boxColStart = col - col % sqrt;
for (int r = boxRowStart; r < boxRowStart + sqrt; r++)
{
for (int d = boxColStart; d < boxColStart + sqrt; d++)
{
if (board[r][d] == num)
return false;
}
}
return true;
}
public static boolean solve(int[][] board, int n)
{
int row = -1;
int col = -1;
boolean isEmpty = true;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (board[i][j] == 0)
{
row = i;
col = j;
isEmpty = false;
break;
}
}
if (!isEmpty)
break;
}
if (isEmpty)
return true;
for (int num = 1; num <= n; num++)
{
if (isSafe(board, row, col, num))
{
board[row][col] = num;
if (solve(board, n))
return true;
else
board[row][col] = 0;
}
}
return false;
}
public static void print(int[][] board, int N)
{
for (int r = 0; r < N; r++)
{
for (int d = 0; d < N; d++)
{
System.out.print(board[r][d]);
System.out.print(" ");
}
System.out.print("\n");
if ((r + 1) % (int) Math.sqrt(N) == 0)
System.out.print("");
}
}
public static void main(String[] args) throws IOException {
final int[][] STORED = {{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
int[][] puzzle = STORED;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int c, r, d;
int N = puzzle.length;
int[][] board = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++)
board[i][j] = STORED[i][j];
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++){}
//System.out.print(board[i][j] + " ");
System.out.println();
}
System.out.println();
if (solve(puzzle, N)) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++)
System.out.print(STORED[i][j] + " ");
System.out.println();
}
}