问题:
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.
分析:先分析行;再分析列;最后分析九宫格。前两个都好说,第三个要注意index。
代码:
class Solution {
public:
bool isValidSudoku(vector<vector<char> > &board) {
// row
for (int i = 0; i < 9; i ++) {
vector<bool> numbers (9, false);
for (int j = 0; j < 9; j ++) {
char c = board[i][j];
if (c == '.') continue;
if (numbers[c - '0' - 1] == true)
return false;
else
numbers[c - '0' - 1] = true;
}
}
// col
for (int i = 0; i < 9; i ++) {
vector<bool> numbers(9, false);
for (int j = 0; j < 9; j ++) {
char c = board[j][i];
if (c == '.') continue;
if (numbers[c - '0' - 1] == true)
return false;
else
numbers[c - '0' - 1] = true;
}
}
// nines
for (int i = 0; i < 9; i ++) {
vector<bool> numbers(9, false);
for (int j = 0; j < 9; j ++) {
int a = 3 * (i / 3) + j / 3; // row
int b = (j % 3) + (i % 3) * 3; // col
char c = board[a][b];
if (c == '.') continue;
if (numbers[c - '0' - 1] == true)
return false;
else
numbers[c - '0' - 1] = true;
}
}
return true;
}
};