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

感谢阅读!

相关推荐
დ旧言~20 分钟前
【高阶数据结构】图论
算法·深度优先·广度优先·宽度优先·推荐算法
张彦峰ZYF24 分钟前
投资策略规划最优决策分析
分布式·算法·金融
The_Ticker40 分钟前
CFD平台如何接入实时行情源
java·大数据·数据库·人工智能·算法·区块链·软件工程
Lenyiin1 小时前
02.06、回文链表
数据结构·leetcode·链表
爪哇学长1 小时前
双指针算法详解:原理、应用场景及代码示例
java·数据结构·算法
Dola_Pan1 小时前
C语言:数组转换指针的时机
c语言·开发语言·算法
繁依Fanyi2 小时前
简易安卓句分器实现
java·服务器·开发语言·算法·eclipse
烦躁的大鼻嘎2 小时前
模拟算法实例讲解:从理论到实践的编程之旅
数据结构·c++·算法·leetcode
C++忠实粉丝2 小时前
计算机网络socket编程(4)_TCP socket API 详解
网络·数据结构·c++·网络协议·tcp/ip·计算机网络·算法
祁思妙想2 小时前
10.《滑动窗口篇》---②长度最小的子数组(中等)
leetcode·哈希算法