当前位置: 首页 > 图灵资讯 > 技术篇> LeetCode程序员面试金典:有效的数独

LeetCode程序员面试金典:有效的数独

来源:图灵教育
时间:2023-04-27 09:24:18

  题目:

  请判断一个9 x 9 数独是否有效。只需要 根据以下规则 ,验证已填写的数字是否有效。

  每行只能出现一次数字1-9。

  每列只能出现一次数字1-9。

  数字1-9只能出现在每个3x3宫,每个3x3宫以粗实线分隔。(请参考示例图)

  注意:

  一个有效的数独(部分已经填满)不一定是可解的。

  只需根据上述规则验证已填写的数字是否有效。

  空白格用'.'表示。

  示例 1:

  输入:board =

  [[[5”,“3”,.",".","七",".",".",".","."]

  ,["6",".","."一","九","五",".",".","."]

  ,["."九","八",".",".",".","."六","."]

  ,["8",".",".","."六",".",".",".","3"]

  ,["4",".",".","八".","三".",".","1"]

  ,["7",".",".",".","二".",".",".","6"]

  ,["."六",".",".",".",".","二","八"."]

  ,[".",".","."四","一","九",".",".","5"]

  ,[".",".",".",".","八".",".","7","9"]"

  输出:true

  示例 2:

  输入:board =

  [“8”,“3”,.",".","七",".",".",".","."]

  ,["6",".","."一","九","五",".",".","."]

  ,["."九","八",".",".",".","."六","."]

  ,["8",".",".","."六",".",".",".","3"]

  ,["4",".",".","八".","三".",".","1"]

  ,["7",".",".",".","二".",".",".","6"]

  ,["."六",".",".",".",".","二","八"."]

  ,[".",".","."四","一","九",".",".","5"]

  ,[".",".",".",".","八".",".","7","9"]"

  输出:false

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

  代码实现:class Solution { public boolean isValidSudoku(char[][] board) { int[][] rows = new int[9][9]; int[][] columns = new int[9][9]; int[][][][][][][][][] subboxes = new int[3][3][9]; 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; }}