力扣经典150题解析之三十四:有效的数独

目录

解题思路与实现 - 有效的数独

问题描述

判断一个 9 x 9 的数独是否有效,根据以下规则验证已经填入的数字是否有效:

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 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

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

解题思路
  1. 遍历数独,分别使用三个二维数组 rowscolsboxes 来记录每行、每列以及每个 3x3 宫内出现的数字情况。
  2. 对于每个数字,判断它在当前行、当前列和当前 3x3 宫内是否已经出现过,若出现过则说明数独无效。
  3. 遍历结束后,若没有发现任何冲突,则数独有效。
算法实现
java 复制代码
public boolean isValidSudoku(char[][] board) {
    boolean[][] rows = new boolean[9][9];
    boolean[][] cols = new boolean[9][9];
    boolean[][] boxes = new boolean[9][9];
    
    for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
            if (board[i][j] != '.') {
                int num = board[i][j] - '1';
                int boxIndex = (i / 3) * 3 + (j / 3);
                
                if (rows[i][num] || cols[j][num] || boxes[boxIndex][num]) {
                    return false; // 重复出现
                }
                
                rows[i][num] = true;
                cols[j][num] = true;
                boxes[boxIndex][num] = true;
            }
        }
    }
    
    return true;
}
复杂度分析
  • 时间复杂度:O(1),因为固定为 9 x 9 的数独,算法的时间复杂度是常数级别的。
  • 空间复杂度:O(1),同样因为固定为 9 x 9 的数独,额外空间的大小也是常数级别的。
测试与验证

设计不同的数独输入,包括有效的和无效的情况,验证算法的正确性和效率。

总结

通过本文的详细解题思路和算法实现,可以有效地判断给定的数独是否有效。利用三个二维数组记录每行、每列和每个 3x3 宫内的数字出现情况,然后进行遍历验证,实现了对数独的有效性检查。

感谢阅读!

相关推荐
励志成为嵌入式工程师2 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
师太,答应老衲吧2 小时前
SQL实战训练之,力扣:2020. 无流量的帐户数(递归)
数据库·sql·leetcode
捕鲸叉2 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer2 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
wheeldown3 小时前
【数据结构】选择排序
数据结构·算法·排序算法
观音山保我别报错4 小时前
C语言扫雷小游戏
c语言·开发语言·算法
TangKenny5 小时前
计算网络信号
java·算法·华为
景鹤5 小时前
【算法】递归+深搜:814.二叉树剪枝
算法
iiFrankie5 小时前
SCNU习题 总结与复习
算法
Dola_Pan6 小时前
C++算法和竞赛:哈希算法、动态规划DP算法、贪心算法、博弈算法
c++·算法·哈希算法