# 有效的数独——数组、哈希表、矩阵

> 发布于：2022-03-03 | 分类：刷题 | 原文：https://www.imbailey.cn/post/valid-sudoku-array-hash-table-matrix

> 该题目来自：https://leetcode-cn.com/problems/valid-sudoku/

## 题目

#### [36. 有效的数独](https://leetcode-cn.com/problems/valid-sudoku/)

难度中等786收藏分享切换为英文接收动态反馈

请你判断一个 `9 x 9` 的数独是否有效。只需要 **根据以下规则** ，验证已经填入的数字是否有效即可。

1. 数字 `1-9` 在每一行只能出现一次。
2. 数字 `1-9` 在每一列只能出现一次。
3. 数字 `1-9` 在每一个以粗实线分隔的 `3x3` 宫内只能出现一次。（请参考示例图）

 

**注意：**

- 一个有效的数独（部分已被填充）不一定是可解的。
- 只需要根据以上规则，验证已经填入的数字是否有效即可。
- 空白格用 `'.'` 表示。

 

**示例 1：**

![img](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2021/04/12/250px-sudoku-by-l2g-20050714svg.png)

```
输入：board = 
[["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
```

**示例 2：**

```
输入：board = 
[["8","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"]]
输出：false
解释：除了第一行的第一个数字从 5 改为 8 以外，空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
```

 

**提示：**

- `board.length == 9`
- `board[i].length == 9`
- `board[i][j]` 是一位数字（`1-9`）或者 `'.'`

## 题解

呜呜呜，像我这种臭鱼烂虾也配做出leetcode中等难度的题了吗？

**我的方法，分别扫描行、扫描列、扫描九宫格，三次遍历得出结果**：

```c++
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        unordered_set<int> hashset;
        // 扫描行
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                if(board[i][j]!='.'){
                    if(hashset.find(board[i][j])!=hashset.end()){
                    // cout << "出问题了" << i << j << endl;
                    return false;
                }
                hashset.insert(board[i][j]);
                }
               
            }
            hashset.clear();
        }
        // 扫描列
        for(int j=0;j<9;j++){
            for(int i=0;i<9;i++){
                if(board[i][j]!='.'){
                if(hashset.find(board[i][j])!=hashset.end()){
                    // cout << "出问题了" << i << j << endl;
                    return false;
                }
                hashset.insert(board[i][j]);
            }
            }
            hashset.clear();

        }
        // 扫描九宫格
        for(int m=0;m<3;m++){
            for(int n=0;n<3;n++){ //拆成3*3的九宫格
                for(int i=m*3;i<(m+1)*3;i++){
                    for(int j=n*3;j<(n+1)*3;j++){
                        if(board[i][j]!='.'){
                        if(hashset.find(board[i][j])!=hashset.end()){
                            // cout << "出问题了" << i << j << endl;
                            return false;
                        }
                        hashset.insert(board[i][j]);
                    }
                    }
                }
                hashset.clear();
            }
        }
        return true;

    }
};
```

**大佬的方法，一次遍历就行了**：

```c++
class Solution {
public:
    bool isValidSudoku(vector<vector<char>>& board) {
        int rows[9][9];
        int columns[9][9];
        int subboxes[3][3][9];
        
        memset(rows,0,sizeof(rows));
        memset(columns,0,sizeof(columns));
        memset(subboxes,0,sizeof(subboxes));
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c != '.') {
                    int index = c - '0' - 1;
                    rows[i][index]++;
                    columns[j][index]++;
                    subboxes[i / 3][j / 3][index]++;
                    if (rows[i][index] > 1 || columns[j][index] > 1 || subboxes[i / 3][j / 3][index] > 1) {
                        return false;
                    }
                }
            }
        }
        return true;
    }
};

作者：LeetCode-Solution
链接：https://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode-solution-50m6/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
```

节省遍历次数的关键是创建了三个数组，

* `rows[i][index]`记录当前数字`index`在第`i`行出现的次数。
* `columns[j][index]`记录当前数字`index`在第`j`列出现的次数。
* `subboxes[i/3][j/3][index]`记录当前数字`index`在第`[i/3][j/3]`个九宫格中出现的次数。

因为有确定的遍历次数和确定的数组大小，所以时间和空间复杂度都是O(1)
