使用 Choco Solver 求解
package com.example.csp;
import org.chocosolver.solver.Model;
import org.chocosolver.solver.Solver;
import org.chocosolver.solver.variables.IntVar;
public class SudokuSolver {
public static void main(String[] args) {
int[][] puzzle = {
{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[][] solution = solveSudoku(puzzle);
}
public static int[][] solveSudoku(int[][] puzzle) {
Model model = new Model("Sudoku");
IntVar[][] grid = new IntVar[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
grid[i][j] = model.intVar("cell[" + i + "," + j + "]", 1, 9);
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (puzzle[i][j] != 0) {
model.arithm(grid[i][j], "=", puzzle[i][j]).post();
}
}
}
for (int i = 0; i < 9; i++) {
model.allDifferent(grid[i]).post();
}
for (int j = 0; j < 9; j++) {
IntVar[] column = new IntVar[9];
for (int i = 0; i < 9; i++) {
column[i] = grid[i][j];
}
model.allDifferent(column).post();
}
for (int boxRow = 0; boxRow < 3; boxRow++) {
for (int boxCol = 0; boxCol < 3; boxCol++) {
IntVar[] box = new IntVar[9];
int index = 0;
for (int i = boxRow * 3; i < boxRow * 3 + 3; i++) {
for (int j = boxCol * 3; j < boxCol * 3 + 3; j++) {
box[index++] = grid[i][j];
}
}
model.allDifferent(box).post();
}
}
Solver solver = model.getSolver();
if (solver.solve()) {
int[][] solution = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
solution[i][j] = grid[i][j].getValue();
}
}
return solution;
}
return null;
}
}