1 题目
Determine if a 9x9 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 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
2 尝试解
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
map<int,map<int,int>> row;
map<int,map<int,int>> column;
map<int,map<int,int>> square;
//scan the board
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
if(board[i][j]!='.'){
int num = int(board[i][j]-'0');
if(row[i].count(num)==0){row[i][num] = 1;}
else{return false;}
if(column[j].count(num)==0){column[j][num] = 1;}
else{return false;}
if(square[3*(i/3)+j/3].count(num)==0){square[3*(i/3)+j/3][num]=1;}
else{return false;}
}
}
}
return true;
}
};
3 标准解
class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
for(int i = 0; i < board.size(); ++ i)
for(int j = 0; j < board[i].size(); ++ j)
if(board[i][j] != '.')
{
int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
if(used1[i][num] || used2[j][num] || used3[k][num])
return false;
used1[i][num] = used2[j][num] = used3[k][num] = 1;
}
return true;
}
};