LeetCode 37. 解数独 Sudoku Solver

本文介绍了一种通过回溯法解决数独问题的程序实现。该算法遵循数独的基本规则,确保数字1-9在每一行、每一列及每个3x3的宫内仅出现一次。文章提供了一个完整的Java代码示例,展示了如何使用递归和有效性检查来找到数独的解决方案。

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

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

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

空白格用 '.' 表示。

一个数独。

答案被标成红色。

Note:

  • 给定的数独序列只包含数字 1-9 和字符 '.' 。
  • 你可以假设给定的数独只有唯一解。
  • 给定数独永远是 9x9 形式的。

 

public class Solution {
    public void solveSudoku(char[][] board) {
        solve(board);
    }
    private boolean solve(char[][] board) {
         for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j ++) {
                if (board[i][j] =='.') {
                    for (char k = '1'; k <= '9'; k++) {
                        board[i][j] = k;
                        if (isValid(board, i, j) && solve(board)) {
                            return true;
                        }
                        board[i][j] = '.';
                    }
                    return false;
                }
            }
        }
        return true;
    }
    private boolean isValid(char[][] board,int x, int y ) {
        boolean [][] square = new boolean[9][9];
        for (int i = 0; i < 9; i++) {
            if (y != i &&board[x][y] == board[x][i]){
                return false;
            }
        }
        for (int i = 0; i < 9; i++) {
            if (x != i &&board[i][y] == board[x][y]){
                return false;
            }
        }
        for (int i = (x / 3) * 3; i < (x / 3) * 3 + 3; i++) {
            for (int j = (y /3) * 3; j < (y / 3) *3 + 3; j++) {
                if (x != i && y != j && board[i][j] == board[x][y]) {
                    return false;
                }
            }
        }
        return true;
    }

}

### LeetCode Problem 37: Sudoku Solver #### Problem Description The task involves solving a partially filled Sudoku puzzle. The input is represented as a two-dimensional integer array `board` where each element can be either a digit from &#39;1&#39; to &#39;9&#39; or &#39;.&#39; indicating empty cells. #### Solution Approach To solve this problem, one approach uses backtracking combined with depth-first search (DFS). This method tries placing numbers between 1 and 9 into every cell that contains &#39;.&#39;, checking whether it leads to a valid solution by ensuring no conflicts arise within rows, columns, and subgrids[^6]. ```cpp void solveSudoku(vector<vector<char>>& board) { backtrack(board); } bool backtrack(vector<vector<char>> &board){ for(int row = 0; row < 9; ++row){ for(int col = 0; col < 9; ++col){ if(board[row][col] != &#39;.&#39;) continue; for(char num=&#39;1&#39;;num<=&#39;9&#39;;++num){ if(isValidPlacement(board,row,col,num)){ placeNumber(num,board,row,col); if(backtrack(board)) return true; removeNumber(num,board,row,col); } } return false; } } return true; } ``` In the provided code snippet: - A function named `solveSudoku()` initiates the process. - Within `backtrack()`, nested loops iterate over all positions in the grid looking for unassigned spots denoted by &#39;.&#39; - For any such spot found, attempts are made to insert digits ranging from &#39;1&#39; through &#39;9&#39;. - Before insertion, validation checks (`isValidPlacement`) ensure compliance with Sudoku rules regarding uniqueness per row/column/subgrid constraints. - If inserting a number results in reaching a dead end without finding a complete solution, removal occurs before trying another possibility. This algorithm continues until filling out the entire board correctly or exhausting possibilities when returning failure status upward along recursive calls stack frames. --related questions-- 1. How does constraint propagation improve efficiency while solving puzzles like Sudoku? 2. Can genetic algorithms provide alternative methods for tackling similar combinatorial problems effectively? 3. What optimizations could enhance performance further beyond basic DFS/backtracking techniques used here?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值