力扣经典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 宫内的数字出现情况,然后进行遍历验证,实现了对数独的有效性检查。

感谢阅读!

相关推荐
古希腊掌管学习的神几秒前
[搜广推]王树森推荐系统笔记——曝光过滤 & Bloom Filter
算法·推荐算法
qystca2 分钟前
洛谷 P1706 全排列问题 C语言
算法
古希腊掌管学习的神6 分钟前
[LeetCode-Python版]相向双指针——611. 有效三角形的个数
开发语言·python·leetcode
浊酒南街7 分钟前
决策树(理论知识1)
算法·决策树·机器学习
就爱学编程15 分钟前
重生之我在异世界学编程之C语言小项目:通讯录
c语言·开发语言·数据结构·算法
ProcessOn官方账号17 分钟前
如何绘制网络拓扑图?附详细分类解说和用户案例!
网络·职场和发展·流程图·拓扑学
学术头条20 分钟前
清华、智谱团队:探索 RLHF 的 scaling laws
人工智能·深度学习·算法·机器学习·语言模型·计算语言学
Schwertlilien1 小时前
图像处理-Ch4-频率域处理
算法
IT猿手1 小时前
最新高性能多目标优化算法:多目标麋鹿优化算法(MOEHO)求解TP1-TP10及工程应用---盘式制动器设计,提供完整MATLAB代码
开发语言·深度学习·算法·机器学习·matlab·多目标算法
__lost1 小时前
MATLAB直接推导函数的导函数和积分形式(具体方法和用例)
数学·算法·matlab·微积分·高等数学