本文共 898 字,大约阅读时间需要 2 分钟。
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:
判断一个数独是否有效,开始时理解错题意了,这里只管数独是否有效,而不需要关心填上的数字是否能解开这个数独。
所以就是判断每行,每列,每块不能有重复数字。O(N^2)。 其中第二个方法是bit操作,有意思!class Solution {public: bool isValidSudoku(vector>& board) { bool num1[9][9]={ 0},num2[9][9]={ 0},num3[9][9]={ 0}; for(int i=0;i >& board) { vector col(9, 0); vector block(9, 0); vector row(9, 0); for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { int idx = 1 << (board[i][j] - '0'); if (row[i] & idx || col[j] & idx || block[i/3 * 3 + j / 3] & idx) return false; row[i] |= idx; col[j] |= idx; block[i/3 * 3 + j/3] |= idx; } } return true; }};
转载地址:http://oexvi.baihongyu.com/