【LeetCode】036. Valid Sudoku

时间:2023-03-09 18:26:04
【LeetCode】036. Valid Sudoku

题目:

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.

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

【LeetCode】036. Valid Sudoku

A partially filled sudoku which is valid.

Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

题解:

Solution 1

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
const int n = ; for(int i = ; i < n; ++i){
bool used[n] = {false};
for(int j = ; j < n; ++j){
if(isused(board[i][j], used))
return false;
}
}
for(int i = ; i < n; ++i){
bool used[n] = {false};
for(int j = ; j < n; ++j){
if(isused(board[j][i], used))
return false;
}
}
for(int r = ; r < ; ++r){
for(int c = ; c < ; ++c){
bool used[n] = {false};
for(int i = r * ; i < r * + ; ++i){
for(int j = c * ; j < c * + ; ++j){
if(isused(board[i][j], used))
return false;
}
}
}
}
return true;
}
bool isused(char val, bool used[]){
if(val == '.')
return false;
if(used[val - ''])
return true;
used[val - ''] = true;
return false;
}
};

Solution 2

class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
const int n = ;
vector<vector<bool>> rowboard(n, vector<bool>(n, false));
vector<vector<bool>> colboard(n, vector<bool>(n, false));
vector<vector<bool>> celboard(n, vector<bool>(n, false));
for(int i = ; i < n; ++i){
for(int j = ; j < n; ++j){
if(board[i][j] == '.') continue;
int ch = board[i][j] - '';
if(rowboard[i][ch] || colboard[ch][j] || celboard[ * (i / ) + j / ][ch])
return false;
rowboard[i][ch] = true;
colboard[ch][j] = true;
celboard[ * (i / ) + j / ][ch] = true;
}
}
return true;
}
};