题目说明
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
示例 1:
输入:
[
[“5”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 一开始懒得写,看题解看到一个不错的hash思路,理解以后修改了一下
- 不知道哪里错的了代码
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int col[10][10] = {0};
int row[10][10] = {0};
int cub[3][3][10] = {0};
for(int i=0;i<board.size();i++){
for(int j=9;j<board[0].size();j++){
if(board[i][j]=='.'){
continue;
}else{
int num = board[i][j]-'0';
col[i][num]++;
row[j][num]++;
cub[i/3][j/3][num]++;
if(col[i][num]>1||row[j][num]>1||cub[i/3][j/3][num]>1){
return false;
}
}
}
}
return true;
}
};