题目
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 '.'
.
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.
分析
数独规则是每行每列以及没个小方框中的数字都是0~9且都没有重复的数字。
所以就分别遍历每行、每列以及没个小方框,判断有无重复的数字即可。
实现
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for(int i=0; i<9; i++){
int trow[9]={0}, tcol[9]={0}, tblk[9]={0};
for(int j=0; j<9; j++){
if(board[i][j]!='.'){
int nrow = board[i][j] - '0' - 1;
if(trow[nrow]) return false;
trow[nrow]++;
}
if(board[j][i]!='.'){
int ncol = board[j][i] - '0' - 1;
if(tcol[ncol]) return false;
tcol[ncol]++;
}
int x = i / 3 * 3 + j / 3;
int y = i % 3 * 3 + j % 3;
if(board[x][y]!='.'){
int nblk = board[x][y] - '0' - 1;
if(tblk[nblk]) return false;
tblk[nblk]++;
}
}
}
return true;
}
};
思考
在这里没有判断出现除'1'~'9'和'.'之外的符号怎么办,严谨点应该加上。