Here we have some simplest way to check the sudoku validation. And we have few discussion and suggestion on this post comments section, so we decided to give the solution as per the discussion.
Coding snippet:
private static boolean check(){
int[][] l_arrSudukoMatrix = new int[][] {
{ 5, 1, 3, 6, 8, 7, 2, 4, 9 },
{ 8, 4, 9, 5, 2, 1, 6, 3, 7 },
{ 2, 6, 7, 3, 4, 9, 5, 8, 1 },
{ 1, 5, 8, 4, 6, 3, 9, 7, 2 },
{ 9, 7, 4, 2, 1, 8, 3, 6, 5 },
{ 3, 2, 6, 7, 9, 5, 4, 1, 8 },
{ 7, 8, 2, 9, 3, 4, 1, 5, 6 },
{ 6, 3, 5, 1, 7, 2, 8, 9, 4 },
{ 4, 9, 1, 8, 5, 6, 7, 2, 3 } }; //valid
for(int i = 0 ; i < l_arrSudukoMatrix.length; i++){
int sumRow = 0;
int sumColumn = 0;
int col = 0;
for(int j = 0 ; j < l_arrSudukoMatrix.length; j++){
sumColumn += l_arrSudukoMatrix[i][j];
sumRow += l_arrSudukoMatrix[j][i];
col = j;
}
if(sumRow != 45 || sumColumn != 45){
System.out.println("invalid");
return false;
}
}
System.out.println("valid");
return true;
}
Output: valid
If you change input array to duplicate any value in row or column you will get output like this.
Input:
int[][] l_arrSudukoMatrix = new int[][] {
{ 5, 1, 3, 6, 8, 7, 2, 4, 9 },
{ 8, 4, 9, 5, 2, 1, 6, 3, 7 },
{ 2, 6, 7, 3, 4, 9, 5, 8, 1 },
{ 1, 5, 8, 4, 6, 3, 9, 7, 2 },
{ 9, 7, 4, 2, 1, 8, 3, 6, 5 },
{ 3, 2, 6, 7, 9, 5, 4, 1, 0 }, //0 is not a valid one.
{ 7, 8, 2, 9, 3, 4, 1, 5, 6 },
{ 6, 3, 5, 1, 7, 2, 8, 9, 4 },
{ 4, 9, 1, 8, 5, 6, 7, 2, 3 } };
Ouput: Invalid
Thank you.