力扣数组练习题(有效的数独、解数独)

168 阅读5分钟

有效的数独

来源:力扣(LeetCode) 链接:leetcode.cn/problems/va…

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

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

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

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

注意:

  • 一个有效的数独(部分已被填充)不一定是可解的。

  • 只需要根据以上规则,验证已经填入的数字是否有效即可。

  • 空白格用 '.' 表示。

示例 1:

图片.png

输入:board = 
[["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:

输入:board = 

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

提示:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] 是一位数字(1-9)或者 '.'

代码

class Solution {
    public boolean isValidSudoku(char[][] board) {
        // Initialize row, column, and sub-box sets
        Set<Integer>[] rows = new HashSet[9];
        Set<Integer>[] cols = new HashSet[9];
        Set<Integer>[] boxes = new HashSet[9];
        for (int i = 0; i < 9; i++) {
            rows[i] = new HashSet<>();
            cols[i] = new HashSet<>();
            boxes[i] = new HashSet<>();
        }
        
        // Iterate through each cell in the board
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c = board[i][j];
                if (c == '.') {
                    continue;
                }
                
                // Check if the cell value is already in the corresponding row, column, or sub-box
                int num = c - '0';
                if (rows[i].contains(num) || cols[j].contains(num) || boxes[(i / 3) * 3 + j / 3].contains(num)) {
                    return false;
                }
                
                // Add the cell value to the corresponding row, column, and sub-box sets
                rows[i].add(num);
                cols[j].add(num);
                boxes[(i / 3) * 3 + j / 3].add(num);
            }
        }
        
        // All cells are valid
        return true;
    }
}

思路分析

这个算法的时间复杂度为O(1),因为它只对一个9x9的矩阵进行迭代,且每个格子只访问一次。它使用集合来检查数独是否有效。

这个算法的思路是,对于每个非空的格子,我们要检查它是否满足数独的三个条件:在同一行中没有重复数字,同一列中没有重复数字,同一个3x3的子数独中没有重复数字。为了实现这个目标,我们可以用三个集合来存储每个数字在当前行、当前列、当前子数独中是否已经出现过。对于每个非空格子,我们将它的数字加入到对应的集合中。如果在任意一个集合中已经存在该数字,则数独无效,我们可以直接返回false。否则,我们可以将这个数字加入到三个集合中。当迭代完成后,如果所有格子都满足数独的三个条件,则数独有效。

这个算法的优点是它简单,时间复杂度为O(1),空间复杂度为O(1)。缺点是它使用了多个集合,需要占用较多的空间。

解数独

来源:力扣(LeetCode) 链接:leetcode.cn/problems/su…

编写一个程序,通过填充空格来解决数独问题。

数独的解法需 遵循如下规则:

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

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

示例 1:

![图片.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d798998763524ca9af7f121f1dcecd37~tplv-k3u1fbpfcp-watermark.image?)

输入:board = [["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"]]

输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]

解释:输入的数独如上图所示,唯一有效的解决方案如下所示:

图片.png

提示:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] 是一位数字或者 '.'
  • 题目数据 保证 输入数独仅有一个解

代码

class Solution {
    public void solveSudoku(char[][] board) {
        solve(board, 0, 0);
    }
    
    private boolean solve(char[][] board, int row, int col) {
        // If we have reached the end of the board, we have found a valid solution
        if (row == 9) {
            return true;
        }
        
        // If we have reached the end of the current row, move to the next row
        if (col == 9) {
            return solve(board, row + 1, 0);
        }
        
        // If the current cell is already filled, move to the next cell
        if (board[row][col] != '.') {
            return solve(board, row, col + 1);
        }
        
        // Try to fill the current cell with each number from 1 to 9
        for (int i = 1; i <= 9; i++) {
            char c = (char) ('0' + i);
            if (isValid(board, row, col, c)) {
                board[row][col] = c;
                if (solve(board, row, col + 1)) {
                    return true;
                }
                board[row][col] = '.';
            }
        }
        
        // None of the numbers from 1 to 9 worked, backtrack
        return false;
    }
    
    private boolean isValid(char[][] board, int row, int col, char c) {
        // Check if the same digit already exists in the same row, column, or box
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == c || board[i][col] == c || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
                return false;
            }
        }
        return true;
    }
}

思路分析

这个算法的时间复杂度是指数级的,因为它尝试了所有可能的填法。但是由于数独的规模是固定的,因此实际运行时间是可接受的。它使用回溯法来解决数独问题。

这个算法的思路是,对于每个空格子,我们尝试用1到9中的数字来填充它,如果填充后不违反数独的规则,我们就递归继续尝试填充下一个空格子。如果所有的空格子都已经填充完毕,我们就找到了一个有效的解。如果在填充过程中发现某个数字填不进去,我们就回溯到上一个格子,换一个数字继续尝试填充。

为了检查当前的填法是否有效,我们需要检查当前行、当前列、以及当前3x3的子数独是否已经包含了我们要填充的数字。这个检查可以通过一次遍历来完成,时间复杂度为O(1)。

这个算法的优点是它能够找到数独的所有有效解,并且它的思路清晰简单。