题目:
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 ‘.’.
Solution:
(1)同一行没有相同的数字。
(2)同一列没有相同的数字
(3)每个子模块(9个)中不能有相同的数字。
(4)’.’,表示没有数字填充的空格,不需比较。只需比较有数字的空格。
代码比较清晰:
bool isValidSudoku(vector<vector<char>>& board)
{
int* Row = new int[9];
int* Col = new int[9];
for(int i =0;i<9;i++)
{
memset(Row,0,9*sizeof(int));
memset(Col,0,9*sizeof(int));
for(int j =0;j<9;j++)
{
if(board[i][j] != '.')
{
if(Row[board[i][j] - '1'] > 0)
return false;
else
Row[board[i][j]-'1']++;
}
if(board[j][i] != '.')
{
if(Col[board[j][i] - '1'] > 0)
return false;
else
Col[board[j][i] - '1']++;
}
}
}
int* block = new int[9];
for(int i =0;i<9;i+=3)
for(int j=0;j<9;j+=3)
{
memset(block,0,9*sizeof(int));
for(int a = 0;a<3;a++)
{
for(int b = 0;b<3;b++)
{
if(board[i+a][j+b] != '.')
{
if(block[board[i+a][j+b]-'1'] > 0)
return false;
else
block[board[i+a][j+b]-'1']++;
}
}
}
}
return true;
}