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)
{
return check_row(board) && check_col(board) && check_block(board);
}
bool check_row(vector<vector<char> > &board)
{
int vis[10];
for(int i = 0; i < 9; i++)
{
memset(vis, 0, sizeof(vis));
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')continue;
if(vis[board[i][j] - '1'])return false;
vis[board[i][j] - '1'] = 1;
}
}
return true;
}
bool check_col(vector<vector<char> > &board)
{
int vis[10];
for(int i = 0; i < 9; i++)
{
memset(vis, 0, sizeof(vis));
for(int j = 0; j < 9; j++)
{
if(board[j][i] == '.')continue;
if(vis[board[j][i] - '1'])return false;
vis[board[j][i] - '1'] = 1;
}
}
return true;
}
bool check_block(vector<vector<char> > &board)
{
int vis[10];
for(int i =0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
memset(vis, 0, sizeof(vis));
for(int r = 0; r < 3; r++)
for(int c = 0; c < 3; c++)
{
int x = i * 3 + r;
int y = j * 3 + c;
char chr = board[x][y];
if(chr == '.')continue;
if(vis[chr - '1'])return false;
vis[chr - '1'] = 1;
}
}
}
return true;
}
};