1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package Backtracking;
public class Sudoku {
private static int [] emptyCell = new int [2] ;
private static int cellsToFill = 0 ;
private static int filledCells = 0 ;
public static int [][] solve(int [][] M) {
cellsToFill = cellsToFill(M) ;
return solve(M, 0, 0) ;
}
private static int [][] solve(int [][] M, int raw, int column) {
if (raw == M.length)
return M ;
for (int n = 1; n < 10; n++) {
if (isValid(M, raw, column, n)) {
M[raw][column] = n ;
emptyCell(M, raw, column) ;
filledCells++ ;
solve(M, emptyCell[0], emptyCell[1]) ;
}
if (filledCells >= cellsToFill)
return M ;
M[raw][column] = 0 ;
}
filledCells-- ;
return M ;
}
private static int cellsToFill(int [][] M) {
int nbCellsToFill = 0 ;
for (int i = 0; i < M.length; i++)
for (int j = 0; j < M[0].length; j++)
if (M[i][j] == 0)
nbCellsToFill++ ;
return nbCellsToFill ;
}
private static void emptyCell(int [][] M, int raw, int column) {
if (raw == M.length)
return ;
for (int j = column; j < M[0].length; j++) {
if (M[raw][j] == 0) {
emptyCell[0] = raw ;
emptyCell[1] = j ;
return ;
}
}
emptyCell(M, raw + 1, 0) ;
}
private static boolean isValid(int [][] M, int raw, int column, int n) {
// Check if n exists in raw
for (int j = 0; j < M[0].length; j++)
if (M[raw][j] == n)
return false ;
// Check if n exists in column
for (int i = 0; i < M.length; i++)
if (M[i][column] == n)
return false ;
// Check if n exists in square
int minColumnIndInSquare = getSquareInd(column) ;
int minRawIndInSquare = getSquareInd(raw) ;
for (int i = minRawIndInSquare; i < minRawIndInSquare + 3; i++) {
for (int j = minColumnIndInSquare; j < minColumnIndInSquare + 3; j++) {
if (M[i][j] == n)
return false ;
}
}
return true ;
}
private static int getSquareInd(int i) {
switch (i) {
case 0 : return 0 ;
case 1 : return 0 ;
case 2 : return 0 ;
case 3 : return 3 ;
case 4 : return 3 ;
case 5 : return 3 ;
default : return 6 ;
}
}
public static void showMatrix(int [][] M) {
for (int i= 0; i < M.length; i++) {
for (int j = 0; j < M.length; j++) {
System.out.print(M[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] M = {{0,0,4,0,0,0,5,0,0},
{0,0,3,2,0,6,9,0,0},
{6,0,0,0,5,0,0,0,3},
{0,4,1,7,0,9,3,5,0},
{0,0,0,0,0,0,0,0,0},
{0,5,6,3,0,2,8,7,0},
{8,0,0,0,3,0,0,0,7},
{0,0,2,9,0,7,1,0,0},
{0,0,7,0,0,0,6,0,0}} ;
System.out.println("Input : ");
Sudoku.showMatrix(M) ;
System.out.println();
System.out.println("Output : ");
Sudoku.showMatrix(Sudoku.solve(M)) ;
}
} |