0% found this document useful (0 votes)
10 views3 pages

Sudoko Code

The document contains a Java class that implements a Sudoku solver. It includes methods to print the Sudoku grid, solve the Sudoku using recursion, and check if placing a digit is safe. The main method initializes a Sudoku puzzle and attempts to solve it, printing the solution if it exists.

Uploaded by

rahulsuthrapu616
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views3 pages

Sudoko Code

The document contains a Java class that implements a Sudoku solver. It includes methods to print the Sudoku grid, solve the Sudoku using recursion, and check if placing a digit is safe. The main method initializes a Sudoku puzzle and attempts to solve it, printing the solution if it exists.

Uploaded by

rahulsuthrapu616
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

public class test2{

public static void printSudoko(int sudoko[][]){


for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
[Link](sudoko[i][j]+" ");
}
[Link]();
}
}

public static boolean SudokoSolver(int sudoko[][],int row,int col)


{
//base
if(row==9 ){
return true;
}

//recursion
int newRow=row;
int newCol=col+1;

if(col+1==9){
newRow=row+1;
newCol=0;
}

if(sudoko[row][col]!=0){
return SudokoSolver(sudoko, newRow, newCol);

for(int digit=1; digit<=9; digit++){


if(isSafe(sudoko, row, col, digit)){
sudoko[row][col]=digit;
if(SudokoSolver(sudoko, newRow, newCol)) {
return true;
}
sudoko[row][col]=0;
}

}
return false;

public static boolean isSafe(int sudoko[][],int row,int col,int


digit){
//column
for(int i=0;i<9;i++){
if(sudoko[i][col]==digit){
return false;
}
}

//Row
for(int j=0;j<9;j++){
if(sudoko[row][j]==digit){
return false;
}
}
//grid
int sr=(row/3)*3;
int sc=(col/3)*3;
for(int i=sr; i<sr+3; i++){
for(int j=sc; j<sc+3; j++){
if(sudoko[i][j]==digit){
return false;
}
}
}
return true;
}

public static void main(String[] args) {

int sudoko[][]={
{0, 0, 8, 0, 0, 0, 0, 0, 0},
{4, 9, 0, 1, 5, 7, 0, 0, 2},
{0, 0, 3, 0, 0, 4, 1, 9, 0},
{1, 8, 5, 0, 6, 0, 0, 2, 0},
{0, 0, 0, 0, 2, 0, 0, 6, 0},
{9, 6, 0, 4, 0, 5, 3, 0, 0},
{0, 3, 0, 0, 7, 2, 0, 0, 4},
{0, 4, 9, 0, 3, 0, 0, 5, 7},
{8, 2, 7, 0, 0, 9, 0, 1, 3}
};

if(SudokoSolver(sudoko, 0, 0)) {
[Link]("Soln Exists");
printSudoko(sudoko);
}else{
[Link]("soln does not Exists");
}
}

You might also like