shriyanshi24jindal

Valid Sudoku

Mar 30th, 2026
21
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 8.18 KB | None | 0 0
  1. class Solution {
  2. public boolean isValidSudoku(char[][] board) {
  3. for(int i=0; i<board.length; i++)
  4. {
  5. for(int j=0; j<board[0].length; j++)
  6. {
  7. char ch = board[i][j];
  8. if(isValid(ch, i, j, board) == false)
  9. return false;
  10. }
  11. }
  12. return true;
  13. }
  14.  
  15. public boolean isValid(char ch, int row, int col, char[][] board)
  16. {
  17. if(board[row][col] == '.')
  18. return true;
  19.  
  20. // traversing over 9*9 matrix
  21. for(int k=0; k<9; k++)
  22. {
  23. // checking in same row
  24. if(board[row][k] == ch && k!=col) // So, k != col ensures we ignore the cell we are currently trying to fill
  25. return false;
  26.  
  27. // checking in same column
  28. if(board[k][col] == ch && k!=row) // So, k != row ensures we ignore the cell we are currently trying to fill
  29. return false;
  30.  
  31. // starting row of the subgrid (3*3)
  32. int n = 3*(row/3) + k/3;
  33. // starting col of the subgrid (3*3)
  34. int m = 3*(col/3) + k%3;
  35.  
  36. // we don’t want to compare the cell with itself.
  37. // If any other cell in the same 3×3 subgrid has ch, it’s not valid
  38. if( (n!=row || m!=col) && (board[n][m] == ch))
  39. return false;
  40. }
  41. return true;
  42. }
  43. }
RAW Paste Data Copied