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 size = board.size(); pair<int, int> points[] = {{0, 0,}, {0, 3}, {0, 6}, {3, 0}, {3, 3}, {3, 6}, {6, 0}, {6, 3}, {6, 6}}; for (int i = 0; i < size; ++i) { vector<int> row_count(size, 0); vector<int> col_count(size, 0); vector<int> box_count(size, 0); for (int j = 0; j < size; ++j) { if (board[i][j] != '.') { if (++row_count[board[i][j] - '1'] > 1) { return false; } } if (board[j][i] != '.') { if (++col_count[board[j][i] - '1'] > 1) { return false; } } int px = points[i].first + j / 3; int py = points[i].second + j % 3; if (board[px][py] != '.') { if (++box_count[board[px][py] - '1'] > 1) { return false; } } } } return true; } };