问题描述
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 digits 1-9 without repetition.
解法思路
直接检验三个规则是否都符合
C++代码
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//直接验证三个规则
for(int i=0;i<9;++i)
{
vector<int> number;
for(int j=0;j<9;++j)
{
if(board[i][j]!='.')
{
for(int k=0;k<number.size();++k)
{
if(board[i][j]==board[i][number[k]]) return false;
}
number.push_back(j);
}
}
vector<int> number2;
for(int j=0;j<9;++j)
{
if(board[j][i]!='.')
{
for(int k=0;k<number2.size();++k)
{
if(board[j][i]==board[number2[k]][i]) return false;
}
number2.push_back(j);
}
}
}
//检验sub-box
for(int i=0;i<9;i=i+3)
{
for(int j=0;j<9;j=j+3)
{
vector<vector<int>> v;
for(int k=i;k<i+3;++k)
{
for(int m=j;m<j+3;++m)
{
if(board[k][m]!='.')
{
for(int a=0;a<v.size();++a)
{
if(board[k][m]==board[v[a][0]][v[a][1]]) return false;
}
v.push_back({k,m});
}
}
}
}
}
return true;
}
};
算法结果
Runtime: 16 ms, faster than 96.32% of C++ online submissions for Valid Sudoku.
Memory Usage: 10.1 MB, less than 97.94% of C++ online submissions for Valid Sudoku.