/** C++
* Valid Sudoku
* 有效的数独
*/
class Solution
{
public:
bool isValidSudoku(vector<vector<char> > &board)
{
const int cnt = 9;
bool row_mask[cnt][cnt] = {false};
bool col_mask[cnt][cnt] = {false};
bool area_mask[cnt][cnt] = {false};
//check each rows and cols
for(int r=0; r<board.size(); r++)
{
for (int c=0; c<board[r].size(); c++)
{
if (!isdigit(board[r][c])) continue;
int idx = board[r][c] - '0' - 1;
//check the rows
if (row_mask[r][idx] == true)
{
return false;
}
row_mask[r][idx] = true;
//check the cols
if (col_mask[c][idx] == true)
{
return false;
}
col_mask[c][idx] = true;
//check the areas
int area = (r/3) * 3 + (c/3);
if (area_mask[area][idx] == true)
{
return false;
}
area_mask[area][idx] = true;
}
}
return true;
}
};
/** Pyhton
* Valid Sudoku
* 有效的数独
*/
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
cacheCol = [[0] * 9 for _ in xrange(0, 10)]
cacheRow = [[0] * 9 for _ in xrange(0, 10)]
cacheBox = [[0] * 9 for _ in xrange(0, 10)]
for i in xrange(0, 9):
for j in xrange(0, 9):
ib = (i/3)*3 + j/3
if board[i][j] == ".":
continue
num = int(board[i][j]) - 1
if cacheRow[i][num] != 0 or cacheCol[j][num] != 0 or cacheBox[ib][num] != 0:
return False
cacheRow[i][num] = 1
cacheCol[j][num] = 1
cacheBox[ib][num] = 1
return True