Not a member of GistPad yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public boolean isValidSudoku(char[][] board) {
- for(int i=0; i<board.length; i++)
- {
- for(int j=0; j<board[0].length; j++)
- {
- char ch = board[i][j];
- if(isValid(ch, i, j, board) == false)
- return false;
- }
- }
- return true;
- }
- public boolean isValid(char ch, int row, int col, char[][] board)
- {
- if(board[row][col] == '.')
- return true;
- // traversing over 9*9 matrix
- for(int k=0; k<9; k++)
- {
- // checking in same row
- if(board[row][k] == ch && k!=col) // So, k != col ensures we ignore the cell we are currently trying to fill
- return false;
- // checking in same column
- if(board[k][col] == ch && k!=row) // So, k != row ensures we ignore the cell we are currently trying to fill
- return false;
- // starting row of the subgrid (3*3)
- int n = 3*(row/3) + k/3;
- // starting col of the subgrid (3*3)
- int m = 3*(col/3) + k%3;
- // we don’t want to compare the cell with itself.
- // If any other cell in the same 3×3 subgrid has ch, it’s not valid
- if( (n!=row || m!=col) && (board[n][m] == ch))
- return false;
- }
- return true;
- }
- }
RAW Paste Data
Copied
