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.
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int col[9]; //列标志位
int row[9]; //行标志位
//检查行和列
for(int i = 0; i < 9; i++)
{
memset(col, 0, sizeof(int)*9);
memset(row, 0, sizeof(int)*9);
for(int j = 0; j < 9; j++)
{
if(board[i][j] != '.')
{
if(row[board[i][j] - '1'])
return false;
row[board[i][j] - '1'] = 1;
}
if(board[j][i] != '.')
{
if(col[board[j][i] - '1'])
return false;
col[board[j][i] - '1'] = 1;
}
}
}
//检查3*3方块
for(int i = 0; i < 9; i+=3)
{
for(int j = 0; j < 9; j+=3)
{
memset(col, 0, sizeof(int)*9);
for(int m = 0; m < 3; m++)
{
for(int n = 0; n < 3; n++)
{
if(board[i+m][j+n] != '.')
{
if(col[board[i+m][j+n] - '1'])
return false;
col[board[i+m][j+n] - '1'] = 1;
}
}
}
}
}
return true;
}
};