Question: Here I have a code that displays and gives solution so how can I amke it so I am righting my answer but if its

Here I have a code that displays and gives solution so how can I amke it so I am righting my answer but if its wrong it says incorrect and if I am right it says correct will still showing the solution?
import java.util.Scanner;
public class Sudoku {
public boolean isSafe(int[][] b, int r, int c, int num){
// Check if 'num' is not present in the current row and column
for (int i =0; i <9; i++){
if (b[r][i]== num || b[i][c]== num){
return false;
}
}
// Check if 'num' is not present in the 3x3 grid
int startRow = r -(r %3);
int startCol = c -(c %3);
for (int i =0; i <3; i++){
for (int j =0; j <3; j++){
if (b[i + startRow][j + startCol]== num){
return false;
}
}
}
return true;
}
public boolean solveSudoku(int[][] b){
int n = b.length;
// Find an empty location
int[] empty = findEmptyLocation(b);
int row = empty[0];
int col = empty[1];
// If there is no empty location, the puzzle is solved
if (row ==-1 && col ==-1){
return true;
}
// Try filling the empty location with a number
for (int num =1; num <=9; num++){
if (isSafe(b, row, col, num)){
b[row][col]= num;
// Recursively try to solve the rest of the puzzle
if (solveSudoku(b)){
return true;
}
// If placing 'num' at the current location doesn't lead to a solution, backtrack
b[row][col]=0;
}
}
// If no number can be placed at the current location, backtrack
return false;
}
private int[] findEmptyLocation(int[][] b){
int[] location = new int[]{-1,-1};
for (int i =0; i <9; i++){
for (int j =0; j <9; j++){
if (b[i][j]==0){
location[0]= i;
location[1]= j;
return location;
}
}
}
return location;
}
public void display(int[][] b){
for (int i =0; i <9; i++){
for (int j =0; j <9; j++){
System.out.print(b[i][j]+"");
}
System.out.println();
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
// Take user input for the initial Sudoku grid
System.out.println("Enter the Sudoku grid (0 for empty cells):");
int[][] b = new int[9][9];
for (int i =0; i <9; i++){
for (int j =0; j <9; j++){
b[i][j]= scanner.nextInt();
}
}
Sudoku obj = new Sudoku();
System.out.println("The initial grid is: ");
obj.display(b);
if (obj.solveSudoku(b)){
System.out.println("The solution of the grid is: ");
obj.display(b);
} else {
System.out.println("There is no solution available.");
}
scanner.close();
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!