[LeetCode] Valid Sudoku

36. Valid Sudoku

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

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

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
unordered_set<string> s;

for(int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
if(board[row][col] == '.') continue;
string rowVal = "row" + to_string(row) + board[row][col];
string colVal = "col" + to_string(col) + board[row][col];
string cellVal = "cell" + to_string(row / 3 * 3 + col / 3) + board[row][col];
if(s.count(rowVal) || s.count(colVal) || s.count(cellVal)) {
return false;
}
s.insert(rowVal);
s.insert(colVal);
s.insert(cellVal);
}
}
return true;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
bool rows[9][9] {false, }, cols[9][9] {false, }, cells[9][9] {false, };

for(int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
if(board[row][col] == '.') continue;
if(rows[row][(board[row][col] & 0b1111) - 1] || cols[col][(board[row][col] & 0b1111) - 1] || cells[row / 3 * 3 + col / 3][(board[row][col] & 0b1111) - 1] )
return false;
rows[row][(board[row][col] & 0b1111) - 1] = cols[col][(board[row][col] & 0b1111) - 1] = cells[row / 3 * 3 + col / 3][(board[row][col] & 0b1111) - 1] = true;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/23/PS/LeetCode/valid-sudoku/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.