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.
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
bool exist[10];
//check row
for(int i=0;i<9;i++)
{
for(int k=0;k<9;k++) exist[k+1]=false;;
for(int j=0;j<9;j++)
if(board[i][j]!='.')
{
if(exist[board[i][j]-'0']) return false;
exist[board[i][j]-'0']=true;
}
}
//check column
for(int i=0;i<9;i++)
{
for(int k=0;k<9;k++) exist[k+1]=false;
for(int j=0;j<9;j++)
if(board[j][i]!='.')
{
if(exist[board[j][i]-'0']) return false;
exist[board[j][i]-'0']=true;
}
}
//check square
for(int di=0;di<9;di+=3)
for(int dj=0;dj<9;dj+=3)
{
for(int k=0;k<9;k++) exist[k+1]=false;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
char c=board[di+i][dj+j];
if(c!='.')
{
if(exist[c-'0']) return false;
exist[c-'0']=true;
}
}
}
return true;
}
};
public:
bool isValidSudoku(vector<vector<char> > &board) {
bool exist[10];
//check row
for(int i=0;i<9;i++)
{
for(int k=0;k<9;k++) exist[k+1]=false;;
for(int j=0;j<9;j++)
if(board[i][j]!='.')
{
if(exist[board[i][j]-'0']) return false;
exist[board[i][j]-'0']=true;
}
}
//check column
for(int i=0;i<9;i++)
{
for(int k=0;k<9;k++) exist[k+1]=false;
for(int j=0;j<9;j++)
if(board[j][i]!='.')
{
if(exist[board[j][i]-'0']) return false;
exist[board[j][i]-'0']=true;
}
}
//check square
for(int di=0;di<9;di+=3)
for(int dj=0;dj<9;dj+=3)
{
for(int k=0;k<9;k++) exist[k+1]=false;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
char c=board[di+i][dj+j];
if(c!='.')
{
if(exist[c-'0']) return false;
exist[c-'0']=true;
}
}
}
return true;
}
};