难度:中等 题目来源:力扣(LeetCode) https://leetcode-cn.com/problems/valid-sudoku

    说明:
    判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

    1. 数字 1-9 在每一行只能出现一次。
    2. 数字 1-9 在每一列只能出现一次。
    3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

    image.png
    上图是一个部分填充的有效的数独。
    数独部分空格内已填入了数字,空白格用 '.' 表示。

    示例:
    示例 1:

    输入: [ [“5”,”3”,”.”,”.”,”7”,”.”,”.”,”.”,”.”],

    1. ["6",".",".","1","9","5",".",".","."],
    2. [".","9","8",".",".",".",".","6","."],
    3. ["8",".",".",".","6",".",".",".","3"],
    4. ["4",".",".","8",".","3",".",".","1"],
    5. ["7",".",".",".","2",".",".",".","6"],
    6. [".","6",".",".",".",".","2","8","."],
    7. [".",".",".","4","1","9",".",".","5"],
    8. [".",".",".",".","8",".",".","7","9"]

    ]

    输出: true

    示例 2:

    输入:

    [

    1. ["8","3",".",".","7",".",".",".","."],
    2. ["6",".",".","1","9","5",".",".","."],
    3. [".","9","8",".",".",".",".","6","."],
    4. ["8",".",".",".","6",".",".",".","3"],
    5. ["4",".",".","8",".","3",".",".","1"],
    6. ["7",".",".",".","2",".",".",".","6"],
    7. [".","6",".",".",".",".","2","8","."],
    8. [".",".",".","4","1","9",".",".","5"],
    9. [".",".",".",".","8",".",".","7","9"]

    ]

    输出: false

    解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。

    解法:

    1. func isValidSudoku(board [][]byte) bool {
    2. var row, col, block [9]uint16
    3. var cur uint16
    4. for i := 0; i < 9; i++ {
    5. for j := 0; j < 9; j++ {
    6. if board[i][j] == '.' {
    7. continue
    8. }
    9. cur = 1 << (board[i][j] - '1') // 当前数字的 二进制数位 位置
    10. bi := i/3 + j/3*3 // 3x3的块索引号
    11. if (row[i]&cur)|(col[j]&cur)|(block[bi]&cur) != 0 { // 使用与运算查重
    12. return false
    13. }
    14. // 在对应的位图上,加上当前数字
    15. row[i] |= cur
    16. col[j] |= cur
    17. block[bi] |= cur
    18. }
    19. }
    20. return true
    21. }