Here is the code:
public class sudoku {
public static void printSudoku(int sudoku[][]){
for(int i = 0; i < sudoku.length; i++){
for(int j = 0; j < sudoku[i].length; j++){
System.out.print(sudoku[i][j] + " ");
}
System.out.println();
}
}
public static void sudokuSolver(int sudoku[][], int i, int j){
if (i == 8 && j == 8) {
printSudoku(sudoku);
return;
}
if (j == sudoku[i].length) {
sudokuSolver(sudoku, i+1, 0);
}
for(int n = 1; n <= 9; n++){
if (isSafe(sudoku, i, j, n)) {
sudoku[i][j] = n;
}
sudokuSolver(sudoku, i, j+1);
}
}
public static boolean isSafe(int sudoku[][], int i, int j, int n){
//row
for(int c = 0; c <= 8; c++){
if (sudoku[i][c] == n) {
return false;
}
}
//col
for(int r = 0; r <= 8; r++){
if (sudoku[r][j] == n) {
return false;
}
}
//matrix
int sr = (i/3)*3, sc = (j/3)*3;
for(int r = sr; r<sr+3;r++){
for(int c = sc; c < sc+3; c++){
if (sudoku[r][c]==n) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
int sudoku[][] = {{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0,0}};
sudokuSolver(sudoku, 0, 0);
}
}
I know that we can solve it using backtracking. But whats wrong with this method and i dont know why the stack is getting overflown as i have set the base case as well.
i was expecting a solved sudoky. Instead i am getting "Stack Overflow Error".
dsa. Thedsatag is forDigital Signature Algorithm.