Here's my solution to checking if a Sudoku board is valid. The algorithm checks the following,
- Rows add up to 45
- Columns add up to 45
- Rows have no duplicates
- Cols have no duplicates
- Every 3X3 sub-grid has no duplicate
Invite comments.
public class Checker {
private int size;
private int[][] board;
public Checker(int size){
this.size = size;
board = new int[size][size];
}
private boolean rowCheck(){
int sum = (size*(size+1))/2;
int count = 0;
for (int i = 0; i <size ; i++) {
for (int j = 0; j < size ; j++) {
count += board[i][j];
}
if(count != sum) return false;
count = 0;
}
return true;
}
private boolean columnCheck(){
int sum =0;
int count = 0;
for (int i = 0; i <size ; i++) {
for (int j = 0; j <size ; j++) {
count += board[j][i];
}
if(count != sum) return false;
count = 0;
}
return true;
}
private boolean checkRowDuplicates(){
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i <size ; i++) {
for (int j = 0; j < size ; j++) {
set.add(board[i][j]);
}
if(set.size() != size) return false;
set = null;
}
return true;
}
private boolean checkColumnDuplicates(){
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i <size ; i++) {
for (int j = 0; j < size ; j++) {
set.add(board[j][i]);
}
if(set.size() != size) return false;
set = null;
}
return true;
}
private boolean checkSubBoardDuplicates(){
return (subBoardTraversal(0,3,0,3) && subBoardTraversal(0,3,3,6) && subBoardTraversal(0,3,6,9) && subBoardTraversal(3,6,0,3)
&& subBoardTraversal(3,6,3,6) && subBoardTraversal(3,6,6,9) && subBoardTraversal(6,9,0,3) && subBoardTraversal(6,9,3,6)
&& subBoardTraversal(6,9,6,9));
}
private boolean subBoardTraversal(int rowStart, int rowFinish, int colStart, int colFinish){
HashSet<Integer> set = new HashSet<>();
for (int i = rowStart; i < rowFinish ; i++) {
for (int j =colStart ; j < colFinish; j++) {
set.add(board[i][j]);
}
if(set.size() != 9) return false;
}
return true;
}
public boolean isValid(){
return(rowCheck() && columnCheck() && checkRowDuplicates() && checkColumnDuplicates() && checkSubBoardDuplicates());
}
public void trace(){
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}
-9 -8 -7 -6 -5 -4 -3 -2 89
is a valid row/column? :) \$\endgroup\$columnCheck
is flawed as the sum is always zero... \$\endgroup\$