I believe my code to be working but it’s showing that the time limit is exceeded, I think the code will definitely take time as I am coding it using recursion and backtracking the lessons I learned for it, so it’s expected to take time, I am pasting my code here, please let me know how can I deal with it:
import java.util.*;
public class Main {
public static void main(String args[]) {
// Your Code Here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] boxes = new int[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
boxes[i][j] = sc.nextInt();
}
}
solveSudoku(boxes,0,0);
}
public static void solveSudoku(int[][] boxes,int row,int col) {
if(row==boxes.length) {
for(int i=0;i<boxes.length;i++) {
for(int j=0;j<boxes.length;j++) {
System.out.print(boxes[i][j]);
}
System.out.println();
}
System.out.println();
return;
}
if(col == boxes[0].length) {
solveSudoku(boxes,row+1,0);
return;
}
for(int i=1;i<=9;i++) {
if(boxes[row][col]==0) {
if(isItSafe(boxes,row,col,i)) {
boxes[row][col] = i;
solveSudoku(boxes,row,col+1);
boxes[row][col] = 0;
}else {
continue;
}
}else {
solveSudoku(boxes,row,col+1);
}
}
}
public static boolean isItSafe(int[][] boxes, int row,int col,int num) {
int r = row;
int c = col;
for(int i=c+1;i<boxes[0].length;i++) {
if(boxes[r][i] == num) {
return false;
}
}
for(int i=c-1;i>=0;i--) {
if(boxes[r][i] == num) {
return false;
}
}
for(int i=r-1;i>=0;i--) {
if(boxes[i][c]==num) {
return false;
}
}
for(int i=r+1;i<boxes.length;i++) {
if(boxes[i][c] == num) {
return false;
}
}
for(int i=r;i<r+3 && i<boxes.length;i++) {
for(int j=c;j<c+3 && (j<boxes.length);j++) {
if(boxes[i][j] == num) {
return false;
}
}
}
for(int i=r;i>r-3 && i>=0;i--) {
for(int j=c;j<c+3 && (j<boxes.length);j++) {
if(boxes[i][j] == num) {
return false;
}
}
}
for(int i=r;i<r+3 && i<boxes.length;i++) {
for(int j=c;j>c-3 && (j>=0);j--) {
if(boxes[i][j] == num) {
return false;
}
}
}
for(int i=r;i>r-3 && i>=0;i--) {
for(int j=c;j>c-3 && (j>=0);j--) {
if(boxes[i][j] == num) {
return false;
}
}
}
return true;
}
}