36. Valid Sudoku
2019-05-25 本文已影响0人
jecyhw
题目链接
https://leetcode.com/problems/valid-sudoku/
解题思路
直接看代码。
代码
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
vector<bool> tag(10, false);
//每3*3格子判断
for (int i = 0; i < 9; i += 3) {
for (int j = 0; j < 9; j += 3) {
zero(tag);
for (int a = i + 2; a >= i; --a) {
for (int b = j + 2; b >= j; --b) {
if (board[a][b] != '.') {
if (tag[board[a][b] - '0']) {
return false;
} else {
tag[board[a][b] - '0'] = true;
}
}
}
}
}
}
//每行的格子判断
for (int i = 0; i < 9; i++) {
zero(tag);
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
if (tag[board[i][j] - '0']) {
return false;
} else {
tag[board[i][j] - '0'] = true;
}
}
}
}
//每列的格子判断
for (int i = 0; i < 9; i++) {
zero(tag);
for (int j = 0; j < 9; j++) {
if (board[j][i] != '.') {
if (tag[board[j][i] - '0']) {
return false;
} else {
tag[board[j][i] - '0'] = true;
}
}
}
}
return true;
}
void zero(vector<bool> &v) {
for (int k = 0; k < v.size(); ++k) {
v[k] = false;
}
}
};