lunes, 7 de septiembre de 2015

Ejemplo de como resolver un SODOKU EN JAVA (jcreator) facil







public class Sodoku {
public static final int DIMENSION =9;
public static void main(String[] args){

int[][] tablero= new int[][] {

{0,7,0, 0,0,0, 0,8,0},
{0,5,0, 6,0,0, 0,0,1},
{0,0,3, 1,4,0, 0,0,0},
{9,0,6, 0,5,0, 3,0,0},
{0,0,0, 0,0,0, 0,0,0},
{0,0,5, 0,2,0, 1,0,7},
{0,0,0, 0,6,5, 7,0,0},
{3,0,0, 0,0,1, 9,2,0},
{0,4,0, 0,0,0, 0,1,0},
};
imprimir(tablero);
if(!resolver(tablero)){
System.out.println("El Sudoku no tiene solución");
}else{
}

}

public static void imprimir(int[][] tablero){
for(int i=0;i<DIMENSION;i++){
if(i%3==0){
System.out.println();
}
for(int j=0; j<DIMENSION;j++){
if(j%3==0){
System.out.print(" ");
}
System.out.print(tablero[i][j]);
}
System.out.println();
}
}
public static boolean resolver(int[][] tablero){
for(int i=0; i<DIMENSION; i++){
for(int j=0; j<DIMENSION; j++){
if(tablero[i][j]!=0){//si es diferente o igual a cero
continue;
}
for(int k=1;k<=9;k++){
if(esPosibleInsertar(tablero,i,j,k)){
tablero[i][j]=k;
boolean b=resolver(tablero);
if(b){
return true;
}
tablero[i][j]=0;
}
}
return false;
}
}
System.out.println("Encontrada solución:");
imprimir(tablero);
return true;
}
public static boolean esPosibleInsertar(int [][] tablero,
int i, int j, int valor){
//Comprueba columna
for(int a=0; a<DIMENSION; a++){
if(a!=i &&tablero[a][j]==valor){
return false;
}
}
//Comprueba fila
for(int a=0; a<DIMENSION; a++){
if(a!=j &&tablero[i][a]==valor){
return false;
}
}
//Comprueba cuadardo
int y= (i/3)*3;
int x= (j/3)*3;
for(int a=0; a<DIMENSION/3;a++){
for(int
b=0;b<DIMENSION/3;b++){
if(a!=i
&&b!=j&&tablero[y+a][x+b]==valor){
return false;
}
}
}
return true;
}
}






CORRIDA DEL PROGRAMA
--------------------Configuration: <Default>--------------------

 070 000 080
 050 600 001
 003 140 000

 906 050 300
 000 000 000
 005 020 107

 000 065 700
 300 001 920
 040 000 010

Encontrada solución:

 471 592 683
 259 683 471
 683 147 259

 916 758 342
 724 316 598
 835 924 167

 192 865 734
 368 471 925
 547 239 816


Process completed.

No hay comentarios:

Publicar un comentario