原题链接: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 ‘.’.
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.
这里不需要验证是否有解,只要符合数独的规则就可以。
C++
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int i,j,k,l,row[10], col[10], grid[10];
if(board.size()!=9 || board[0].size()!=9)return false;
for(i=0;i<9;i++){
memset(row,0,sizeof(row));
for(j=0;j<9;j++){
if(board[i][j]=='.')continue;
if(board[i][j]<'0' || board[i][j]>'9')return false;
int num=board[i][j]-'0';
if(row[num])return false;
row[num]=true;
}
}
for(i=0;i<9;i++){
memset(col,0,sizeof(col));
for(j=0;j<9;j++){
if(board[j][i]=='.')continue;
if(board[j][i]<'0' || board[j][i]>'9')return false;
int num=board[j][i]-'0';
if(col[num])return false;
col[num]=true;
}
}
for(i=0;i<3;i++){
for(j=0;j<3;j++){
memset(grid,0,sizeof(grid));
for(k=i*3;k<i*3+3;k++){
for(l=j*3;l<j*3+3;l++){
if(board[k][l]=='.')continue;
int num=board[k][l]-'0';
if(grid[num])return false;
grid[num]=true;
}
}
}
}
return true;
}
};
python
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
seen = []
for pos_r, row in enumerate(board):
for pos_c, value in enumerate(row):
if value != '.':
seen += [(value,pos_c),(pos_r,value),(pos_r/3,pos_c/3,value)]
return len(seen) == len(set(seen))