美文网首页
leetcode 36. 有效的数独(Java版)

leetcode 36. 有效的数独(Java版)

作者: M_lear | 来源:发表于2019-06-09 11:21 被阅读0次

题目描述(题目难度,中等)

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

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

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 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

示例 2:
输入:

  ["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 存在, 因此这个数独是无效的。

说明:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 给定数独序列只包含数字 1-9 和字符 '.'
  • 给定数独永远是 9x9 形式的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目求解

判断数独是否有效,本质上就是对数独中的元素同时做三个判断,即元素所在行是否有重复元素,元素所在列是否有重复元素,元素所在九宫格是否有重复元素。这种判断当前元素在之前的遍历中是否出现过的问题,比较好的解法就是用哈希表。将之前遍历过的信息存起来,然后用 O(1) 的时间复杂度判断当前元素是否在之前出现过。
可以使用 Java 语言提供的 HashMap 作为哈希表,不是不可以,只是效率不是最高的。数独中每个元素对应 3 个哈希表,哈希表用一个长度为 9 的 byte 型数组实现。由于数独的每行对应一个哈希表,每列对应一个哈希表,每个九宫格对应一个哈希表,所以共需要 27 个长度为 9 的 byte 数组,综合起来就是 27*9 的二维数组。

每个元素(i , j)与其对应的三个哈希表的索引关系为:
i,前 9 个哈希表对应数独的行;
9 + j,中间 9 个哈希表对应数独的列;
18 + i/3*3 + j/3,最后 9 个哈希表对应数独的九宫格;

参考代码:

public boolean isValidSudoku(char[][] board) {
    byte[][] hash = new byte[27][9]; // 默认值为 0
    int v;
    for(int i = 0; i < 9; ++i){
        for(int j = 0; j < 9; ++j){
            if(board[i][j] == '.'){
                continue;
            }else{
                v = board[i][j]-49; // '1' 变 0,...,'9' 变 8
                if(hash[i][v] == 1 || hash[9+j][v] == 1 || hash[18+i/3*3+j/3][v] == 1){
                    return false;
                }else{
                    hash[i][v] = 1;
                    hash[9+j][v] = 1;
                    hash[18+i/3*3+j/3][v] = 1;
                }
            }
        }
    }
    return true;
}

相关文章

网友评论

      本文标题:leetcode 36. 有效的数独(Java版)

      本文链接:https://www.haomeiwen.com/subject/xepgxctx.html