Leetcode Valid Sudoku

时间:2022-09-24 13:17:02

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 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.

玩过九宫格的都应该知道规则(没玩过的可以试玩一下九宫格

(1)每行1~9各出现一次

(2)每列1~9各出现一次

(3)每个小的3宫格,1~9各出现一次

class Solution {
public: bool isValidRow(vector<vector<char> >& board){
for(int row = ; row < ; ++ row){
vector<int> cnt(,);
for(int col = ; col < ; ++ col){
char item = board[row][col];
if(item != '.'){
if(cnt[item-'']!=) return false;
else cnt[item-'']++;
}
}
}
return true;
} bool isValidCol(vector<vector<char> >& board ){
for(int col = ; col < ; ++ col){
vector<int> cnt(,);
for(int row = ; row < ; ++ row){
char item = board[row][col];
if(item != '.'){
if(cnt[item-'']!=) return false;
else cnt[item-'']++;
}
}
}
return true;
} bool isValidBox(vector<vector<char> >& board){
for(int i = ; i < ; ++ i){
for(int j = ; j < ; ++ j){
vector<int> cnt(,);
for(int row = *i;row < *i+; ++row){
for(int col = *j; col < *j+; ++col){
char item = board[row][col];
if(item != '.'){
if(cnt[item-'']!=) return false;
else cnt[item-'']++;
}
}
}
}
}
return true;
} bool isValidSudoku(vector<vector<char> > &board) {
return isValidRow(board)&&isValidCol(board)&&isValidBox(board);
}
};