private SudokuGrid iteratePartialSolution(int row, int column, SudokuGrid sudokuGrid) { if (row >= 9) { return sudokuGrid; } iterationCounter++; int newColumn = (column + 1) % 9; int newRow = row + (newColumn == 0 ? 1 : 0); if (sudokuGrid.getFieldValue(row, column) == 0) { for (byte value = 1; value <= 9; value++) { // printDebugInfo(row, column, value); SudokuGrid newSudokuGrid = sudokuGrid.setFieldValue(row, column, value); if (validateSudokuForField(row, column, newSudokuGrid)) { SudokuGrid resultSudokuGrid = iteratePartialSolution(newRow, newColumn, newSudokuGrid); if (resultSudokuGrid != null) { return resultSudokuGrid; } } sudokuGrid.resetFieldValue(row, column); } } else { return iteratePartialSolution(newRow, newColumn, sudokuGrid); } return null; }
private boolean validateRowConstraint(int row, SudokuGrid sudokuGrid) { int[] distinctValueChecker = new int[10]; for (int column = 0; column < 9; column++) { if (sudokuGrid.getFieldValue(row, column) > 0 && (++distinctValueChecker[sudokuGrid.getFieldValue(row, column)]) > 1) { return false; } } return true; }
@Override public byte[][] solve(byte[][] sudoku) { SudokuGrid sudokuGrid = new SudokuModifieableGrid(sudoku); sudokuGrid = iteratePartialSolution(0, 0, sudokuGrid); System.out.println("Number of iterations = " + iterationCounter); if (sudokuGrid != null) { return sudokuGrid.getCanonicalRepresentation(); } else { return null; } }
private boolean validateBlockConstraint(int row, int column, SudokuGrid sudokuGrid) { int[] distinctValueChecker = new int[10]; int blockRowStart = (row / 3) * 3; int blockColumnStart = (column / 3) * 3; for (int blockRow = blockRowStart; blockRow < blockRowStart + 3; blockRow++) { for (int blockColumn = blockColumnStart; blockColumn < blockColumnStart + 3; blockColumn++) { if (sudokuGrid.getFieldValue(blockRow, blockColumn) > 0 && (++distinctValueChecker[sudokuGrid.getFieldValue(blockRow, blockColumn)]) > 1) { return false; } } } return true; }