[Geeks for Geeks] Is Sudoku Valid

Is Sudoku Valid

Given an incomplete Sudoku configuration in terms of a 9x9 2-D square matrix(mat[][]) the task to check if the current configuration is valid or not where a 0 represents an empty block.

Note: Current valid configuration does not ensure validity of the final solved sudoku.

  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution{
int rows[9];
int cells[9];
int cols[9];
public:
int isValid(vector<vector<int>> mat){
memset(rows, 0, sizeof rows);
memset(cells, 0, sizeof cells);
memset(cols, 0, sizeof cols);

for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(!mat[i][j]) continue;
int row = i, col = j, cell = (i / 3) * 3 + (j / 3);
if(rows[row] & (1<<mat[i][j])) return false;
if(cols[col] & (1<<mat[i][j])) return false;
if(cells[cell] & (1<<mat[i][j])) return false;
rows[row] |= 1<<mat[i][j];
cols[col] |= 1<<mat[i][j];
cells[cell] |= 1<<mat[i][j];
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/is-sudoku-valid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.