### How to Check if given Sudoku is Valid or not - The Coding Shala

Home >> Interview Questions >> Valid Sudoku

In Sudoku we need to verify three things. Each row and column must contain the digits 1-9 without repetition and third is Each of the 9, 3*3 boxes of the grid must contain the digits 1-9 without repetition. We can check these things using 3 HashSets or we can take three arrays.

## How to Check if given Sudoku is Valid or not

In this post, you will learn how to check if given Sudoku is valid or not. We will write a Java program to check if the given sudoku board is valid.

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

- Each row must contain the digits 1-9 without repetition.
- Each column must contain the digits 1-9 without repetition.
- Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

**Example:**

For

grid = [['.', '.', '.', '1', '4', '.', '.', '2', '.'],

['.', '.', '6', '.', '.', '.', '.', '.', '.'],

['.', '.', '.', '.', '.', '.', '.', '.', '.'],

['.', '.', '1', '.', '.', '.', '.', '.', '.'],

['.', '6', '7', '.', '.', '.', '.', '.', '9'],

['.', '.', '.', '.', '.', '.', '8', '1', '.'],

['.', '3', '.', '.', '.', '.', '.', '.', '6'],

['.', '.', '.', '.', '.', '7', '.', '.', '.'],

['.', '.', '.', '5', '.', '.', '.', '7', '.']]

## Java Program for Valid Sudoku

**Approach 1:**

In Sudoku we need to verify three things. Each row and column must contain the digits 1-9 without repetition and third is Each of the 9, 3*3 boxes of the grid must contain the digits 1-9 without repetition. We can check these things using 3 HashSets or we can take three arrays.

Java Program:

boolean sudoku2(char[][] grid) { for(int i=0;i<9;i++){ HashSet<Character> row = new HashSet<>(); HashSet<Character> col = new HashSet<>(); HashSet<Character> box = new HashSet<>(); for(int j=0;j<9;j++){ if(grid[i][j]!='.'){ if(row.contains(grid[i][j])) return false; else row.add(grid[i][j]); } if(grid[j][i]!='.'){ if(col.contains(grid[j][i])) return false; else col.add(grid[j][i]); } int row_index = 3*(i/3); int col_index = 3*(i%3); if(grid[row_index + (j/3)][col_index + (j%3)]!='.'){ if(box.contains(grid[row_index + (j/3)][col_index + (j%3)]))

return false; else box.add(grid[row_index + (j/3)][col_index + (j%3)]); } } } return true; }

**Other Posts You May Like**

- Spiral Order Matrix 1
- Anti Diagonals
- Diagonal Traverse
- Search in Rotated Array
- Copy a Linked list with random pointer

## Comments

## Post a Comment