37. Sudoku Solver

本文介绍了一个Sudoku求解器程序的实现方法,通过递归回溯算法填充空单元格来解决数独谜题。文章详细展示了如何验证每个候选数字的有效性以及如何通过深度优先搜索策略找到解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.
非常好理解

代码

public class Solution {
    public void solveSudoku(char[][] board) {
        if(board == null || board.length == 0)
            return;
        solve(board);
    }

    public boolean solve(char[][] board){
        for(int i = 0; i < board.length; i++){  //行
            for(int j = 0; j < board[0].length; j++){  //列
                if(board[i][j] == '.'){
                    for(char c = '1'; c <= '9'; c++){//trial检验. Try 1 through 9 for each cell
                        if(isValid(board, i, j, c)){ //来检验此时这个点所在的行 列  方块
                            board[i][j] = c; //Put c for this cell

                            if(solve(board)) //这步非常重要,每次更新之后再带入
                                return true; //If it's the solution return true
                            else
                                board[i][j] = '.'; //Otherwise go back
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isValid(char[][] board, int i, int j, char c){
        //Check colum
        for(int row = 0; row < 9; row++)
            if(board[row][j] == c)
                return false;

        //Check row
        for(int col = 0; col < 9; col++)
            if(board[i][col] == c)
                return false;

        //Check 3 x 3 block
        for(int row = (i / 3) * 3; row < (i / 3) * 3 + 3; row++)
            for(int col = (j / 3) * 3; col < (j / 3) * 3 + 3; col++)
                if(board[row][col] == c)
                    return false;
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值