Skip to content

Commit

Permalink
Merge pull request #576 from namita27/patch-1
Browse files Browse the repository at this point in the history
Checking if the given board is valid sudoku or not
  • Loading branch information
gantavyamalviya authored Oct 5, 2022
2 parents db7e87e + e23299a commit fbdbb38
Showing 1 changed file with 97 additions and 0 deletions.
97 changes: 97 additions & 0 deletions Hashtable/Checking for a valid sudoku
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import java.util.*;

class example2 {
public static boolean notInRow(char arr[][], int row)
{

HashSet<Character> st = new HashSet<>();

for (int i = 0; i < 9; i++) {
if (st.contains(arr[row][i]))
return false;

if (arr[row][i] != '.')
st.add(arr[row][i]);
}
return true;
}

public static boolean notInCol(char arr[][], int col)
{
HashSet<Character> st = new HashSet<>();

for (int i = 0; i < 9; i++) {

// If already encountered before,
// return false
if (st.contains(arr[i][col]))
return false;

// If it is not an empty cell,
// insert value at the current
// cell in the set
if (arr[i][col] != '.')
st.add(arr[i][col]);
}
return true;
}

public static boolean notInBox(char arr[][], int startRow, int startCol)
{
HashSet<Character> st = new HashSet<>();

for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
char curr = arr[row + startRow][col + startCol];

if (st.contains(curr))
return false;

if (curr != '.')
st.add(curr);
}
}
return true;
}
public static boolean isValid(char arr[][], int row,
int col)
{
return notInRow(arr, row) && notInCol(arr, col)
&& notInBox(arr, row - row % 3, col - col % 3);
}

public static boolean isValidConfig(char arr[][], int n)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {

// If current row or current column or
// current 3x3 box is not valid, return
// false
if (!isValid(arr, i, j))
return false;
}
}
return true;
}

public static void main(String[] args)
{
char[][] board = new char[][] {
{ '5', '3', '.', '.', '7', '.', '.', '.', '.' },
{ '6', '.', '.', '1', '9', '5', '.', '.', '.' },
{ '.', '9', '8', '.', '.', '.', '.', '6', '.' },
{ '8', '.', '.', '.', '6', '.', '.', '.', '3' },
{ '4', '.', '.', '8', '.', '3', '.', '.', '1' },
{ '7', '.', '.', '.', '2', '.', '.', '.', '6' },
{ '.', '6', '.', '.', '.', '.', '2', '8', '.' },
{ '.', '.', '.', '4', '1', '9', '.', '.', '5' },
{ '.', '.', '.', '.', '8', '.', '.', '7', '9' }
};

// Function call
System.out.println(
(isValidConfig(board, 9) ? "YES" : "NO"));
}
}

0 comments on commit fbdbb38

Please sign in to comment.