题目:
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) {
int m = board.size(), n = board[0].size();
vector<int> row(9, 0), col(9, 0), square(9, 0);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(board[i][j] == '.')
continue;
if(board[i][j] < '0' || board[i][j] > '9')
return false;
int val = 1 << (board[i][j] - '0');
if((row[i] & val) || (col[j] & val) || (square[i/3*3+j/3] & val))
return false;
row[i] |= val, col[j] |= val, square[i/3*3+j/3] |= val;
}
}
return true;
}
};