I have written a java program to check if sudoku solution is valid or not, but its not working,
It's giving false for all values, the program logic is correct according to me.
I want to do this without hashsets, and in the simnplest way, hence I have made the program very simple, please dont suggest hashsets or anything but still its not working. Any suggestions on how to fix this program would be of great help.
import java.util.*;
class sudoku {
private int[][] sudoku;
public sudoku() {
sudoku = new int[9][9];
}
public sudoku(int sudoku[][]) {
this.sudoku = sudoku;
}
private boolean containsInRow(int row, int number) {
for (int i = 0; i < 9; i++) {
if (sudoku[row][i] == number) {
return true;
}
}
return false;
}
private boolean containsInCol(int col, int number) {
for (int i = 0; i < 9; i++) {
if (sudoku[i][col] == number) {
return true;
}
}
return false;
}
private boolean containsInBox(int row, int col, int number) {
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i < r + 3; i++) {
for (int j = c; j < c + 3; j++) {
if (sudoku[i][j] == number) {
return true;
}
}
}
return false;
}
private boolean isAllowed(int row, int col, int number) {
boolean checkforCol = containsInCol(col, number);
boolean checkforBox = containsInBox(row, col, number);
boolean checkforRow = containsInRow(row, number);
return !( checkforBox || checkforCol || checkforRow);
}
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int count = 0;
int[][] board =
{
{1,2,3 ,4,5,6, 7,8,9},
{4,5,6 ,7,8,9, 1,2,3},
{7,8,9 ,1,2,3, 4,5,6},
{2,3,1 ,5,6,4, 8,9,7},
{5,6,4 ,8,9,7, 2,3,1},
{8,9,7 ,2,3,1, 5,6,4},
{3,1,2 ,6,4,5, 9,7,8},
{6,4,5 ,9,7,8, 3,1,2},
{9,7,8 ,3,1,2, 6,4,5}
};
sudoku a = new sudoku(board);
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
boolean c = a.isAllowed(i, j, board[i][j] ) ;
if(c == true) {
count++;
}
}
}
if(count == 81) {
System.out.print("Valid");
}
else {
System.out.print("Invalid");
}
}
}