Hallo,
ich wollte einen Sudoku Löser machen,aber ich komme jetzt nicht weiter. Ich verstehe nicht warum in der Ersten Spalte nur Nullen ausgeben werden. Vielleicht kann mir ja jemand einen Tipp geben.
Hier der Code:
Und das Ergebnis:
Lösung:
0 2 4 5 6 7 8 9 3
0 6 1 2 3 8 9 7 5
0 1 5 3 2 9 7 4 8
0 7 6 9 8 1 2 3 4
0 8 3 1 9 4 5 6 2
0 4 9 8 1 6 3 5 7
0 5 2 6 7 3 4 1 9
0 3 8 7 4 5 6 2 1
0 9 7 4 5 2 1 8 6
ich wollte einen Sudoku Löser machen,aber ich komme jetzt nicht weiter. Ich verstehe nicht warum in der Ersten Spalte nur Nullen ausgeben werden. Vielleicht kann mir ja jemand einen Tipp geben.
Hier der Code:
Code:
public class SudokuSolver {
static boolean solve(int i, int j,int Matrix[][]) {
if(i==9 && j==8)
return true; //rechtes unteres Feld erreicht
if(i==9) { // Eine Zeile weiter nach unten
i=0;
j++;
}
if (Matrix[i][j] != 0) { // Nur Felder mit 0 sollen verändert werden
solve(i+1,j,Matrix); //-> gehe einen Schritt weiter
}
for(int value=1; value<=9; value++) { // Alle Zahlen von 1-9 werde getestet
if(save(i, j, value, Matrix)==true) { // Gehe auf nächstes freies Feld
Matrix[i][j]=value; //setze den Wert
if(solve(i+1,j,Matrix)==true)
return true;
}
}
Matrix[i][j]=0; //Feld wird auf Null gesetzt
return false;
}
static boolean save(int i,int j, int value, int Matrix[][]) {
for(int k=0; k<9; k++) { // Zahl in Reihe doppelt
if(value== Matrix[i][k])
return false;
}
for(int k=0; k<9; k++) { // Zahl in Spalte doppelt
if(value== Matrix[k][j])
return false;
}
// Block{
//return false; Zahl im 3*3 Block doppelt
//}
return true; // Zahl ist richtig
}
public static void print(int Matrix[][]) { // Sudoku Ausgabe
System.out.printf("Lösung:");
System.out.println();
for (int x = 0; x < Matrix.length; x++) {
for (int y = 0; y < Matrix.length; y++) {
System.out.print(Matrix[x][y] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int Matrix[][] = // Sudoku was gelöst wird
new int[][] { { 1,0,0,0,0,0,0,0,3},
{ 4,6,0,0,0,0,7,0,0},
{ 6,0,5,0,0,8,0,0,0},
{ 0,7,0,8,0,2,0,3,0},
{ 0,0,2,0,9,0,0,0,0},
{ 0,0,0,0,7,0,0,0,5},
{ 0,0,0,0,0,9,4,0,0},
{ 0,8,0,4,0,0,0,0,1},
{ 3,0,0,0,0,1,0,8,6}};
solve(0, 0, Matrix);
print(Matrix);
//System.out.println(save(0, 0, 3, Matrix));
}
}
Und das Ergebnis:
Lösung:
0 2 4 5 6 7 8 9 3
0 6 1 2 3 8 9 7 5
0 1 5 3 2 9 7 4 8
0 7 6 9 8 1 2 3 4
0 8 3 1 9 4 5 6 2
0 4 9 8 1 6 3 5 7
0 5 2 6 7 3 4 1 9
0 3 8 7 4 5 6 2 1
0 9 7 4 5 2 1 8 6