题目:
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
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-9,且不能重复。
每列必须包含数字1-9,不能重复。
网格的9个3 x 3子框中的每个必须包含数字1-9(无重复)。
只需要把他们分开判断就行了。(因为正好在复习C++模板部分,就在里面尝试着使用了一下)
class Solution {
public:
template <typename T>
bool isRight(vector<T> &arr){
for(auto i : arr){
if(i > 1)return false;
}
return true;
}
template <typename T>
bool check_Row_And_Col(vector<vector<T>>& board){
for(auto i = 0; i < board.size(); i++){
vector<T>row(10, 0);
vector<T>col(10, 0);
for(auto j = 0; j < board.size(); j++)
{
if(board[i][j]!='.'){
auto temp = board[i][j] - '0';
row[temp]++;
}
if(board[j][i]!='.'){
auto temp = board[j][i] - '0';
col[temp]++;
}
}
if(!isRight(row) or !isRight(col))return false;
}
return true;
}
template <typename T>
bool cheak_box(vector<vector<T>>& board){
for(auto i=0; i<board.size(); i += 3)
for(auto j = 0; j < board.size(); j += 3){
vector<T>box(10, 0);
for(auto m = 0; m < 3; m++)
for(auto n = 0; n < 3; n++)
if(board[i+m][j+n] != '.'){
auto temp = board[i+m][j+n] - '0';
box[temp]++;
}
if(!isRight(box))return false;
}
return true;
}
bool isValidSudoku(vector<vector<char>>& board) {
if(check_Row_And_Col(board) and cheak_box(board))
return true;
else return false;
}
};