leetcode 36. Valid Sudoku
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.
嗯,老题目了。定义一个row[9][9]记录第i行j出现了几次,定义一个col[9][9]记录第i列j出现了几次,定义sq[9][9]记录第i个方块j出现了几次。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
array<array<int, 10>, 10> row = {0};
array<array<int, 10>, 10> col = {0};
array<array<int, 10>, 10> sq = {0};
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
if (board[i-1][j-1]!= '.') {
int a = board[i-1][j-1]-'0';
row[i][a] ++;
col[j][a] ++;
int x = (i-1)/3*3+(j-1)/3;
sq[x][a] ++;
}
}
}
int mark = 0;
for (int i = 1; i <= 9; ++i) {
for (int j = 1; j <= 9; ++j) {
if (col[i][j] >= 2 || row[i][j] >= 2 || sq[i-1][j] >= 2) {
mark = 1; break;
}
}
if (mark) break;
}
if (mark) return false;
return true;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: