题目:
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.
提示:
此题最主要的难点其实是如何记录每一块中数字出现的情况(每行和每列比较简单)。
如果我们以从左到右,从上到下的顺序给每一块标定次序的话,那个对于第i行j列的元素,它隶属于i / 3 * 3 + j / 3。
这个问题解决之后,其他问题也就比较简单了。
代码:
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { int mark_row[9][9] = {0}, mark_col[9][9] = {0}, mark_block[9][9] = {0}; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (board[i][j] == '.') continue; int idx = board[i][j] - '1', k = i / 3 * 3 + j / 3; if (mark_row[i][idx] || mark_col[j][idx] || mark_block[k][idx]) return false; else mark_row[i][idx] = mark_col[j][idx] = mark_block[k][idx] = 1; } } return true; } };