A cópia do código é a seguinte:
importar java.util.calendar;
importar java.util.date;
classe pública Matrix {
private int matrix [] [];
Privado longo tempo de tempo de tempo = 0;
Privado longo tempo antes = 0;
Matriz pública (int m [] []) {
matriz = new int [9] [9];
para (int i = 0; i <9; i ++)
for (int j = 0; j <9; j ++)
matriz [i] [j] = m [i] [j];
this.TimeBefore = calendar.getInstance (). getTimeInmillis ();
}
Backtrack public void (int i, int j)
{
// Recursos de memória do sistema de reciclagem
System.gc ();
if (i == 8 && j> = 9)
{
this.timeafter = calendar.getInstance (). gettimeInmillis ();
// matriz de saída bem -sucedida
this.ShowMatrix ();
retornar;
}
if (j == 9) {j = 0;
if (matriz [i] [j] == 0)
{
// O número é zero
for (int k = 1; k <= 9; k ++)
{
if (limitado (i, j, k))
{
matriz [i] [j] = k;
// atende às condições, encontre o próximo quadrado
backtrack (i, j+1);
matriz [i] [j] = 0;
}
}
}outro
{
// O número não é zero, basta procurar o próximo
backtrack (i, j+1);
}
}
/**
* Determine se o número a ser preenchido é duplicado com a mesma coluna e os números na mesma grade de nove
*/
Private Boolean Bound (int i, int j, int k) {
int m = i/3;
int n = j/3;
for (int p = 0; p <9; p ++)
{
if (k == Matrix [i] [p])
{
retornar falso;
}
if (k == Matrix [p] [j])
{
retornar falso;
}
if (k == Matrix [3*m+p/3] [3*n+p%3])
{
retornar falso;
}
}
retornar true;
}
/**
* Imprima o tempo de resolução de problemas
* @retornar
*/
Public Long PrintTime ()
{
devolver this.Timeafter-este.TimeBefore;
}
/**
* Matriz de impressão
*/
public void ShowMatrix ()
{
para (int i = 0; i <9; i ++)
{
for (int j = 0; j <9; j ++)
{
System.out.print (matriz [i] [j]+"");
}
System.out.println ();
}
System.out.println ();
System.out.println ("Tempo de resolução de problemas:"+printTime ()+"ms");
System.out.println ();
}
public static void main (string [] args) {
int matrix [] [] = {
{3,0,6,0,5,7,0,0,0},
{7,9,0,0,2,4,0,0,0},
{0,5,0,6,0,0,9,7,4},
{8,0,1,0,0,9,0,0,0},
{0,2,0,3,0,8,0,0,7},
{4,0,0,0,6,0,5,0,0},
{0,0,4,0,3,6,0,5,0},
{2,0,3,7,0,5,0,0,1},
{0,0,7,4,1,0,6,0,0}};
int ma1 [] [] = {
{0,3,0,0,0,5,0,6,0},
{0,1,0,0,0,3,0,8,0},
{0,4,0,0,0,0,0,0,0,0,7},
{0,0,7,0,2,4,0,0,0},
{5,0,0,0,9,0,0,0,0,0},
{0,8,0,3,0,0,5,0,0},
{0,0,0,8,0,0,0,0,0,0},
{0,0,9,0,0,0,0,0,7,3},
{0,5,0,9,0,0,0,0,0,2}};
int ma2 [] [] = {
{0,0,0,0,8,4,0,0,0}, // 8
{0,0,0,2,0,3,0,8,0},
{8,3,0,9,0,0,0,5,0},
{0,5,3,0,9,0,7,0,0},
{0,0,0,6,3,7,0,4,5}, // 7
{0,7,0,5,0,0,0,0,0,0},
{0,0,6,8,0,0,0,0,0,0},
{3,0,0,0,2,9,0,0,0},
{2,0,9,3,0,0,0,0,1}}; // 3
// é conhecido como o sudoku mais difícil do mundo
int [] [] sudoku = {
{8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 6, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 0}};
Matriz m = nova matriz (sudoku);
M.BackTrack (0, 0);
}
}