(Leetcode)37. Sudoku Solver

本文介绍了一种利用回溯法解决数独问题的方法。通过深度优先搜索策略,遍历可能的解空间树,遇到不符合条件的情况则回溯至上一状态,直至找到正确答案。文章提供了详细的Java代码实现。

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

回溯法(Backtracking)求数独的解

回溯法 Backtracking

深度优先搜索 策略
遍历空间树,找到一个结点。如果符合解的要求,则继续向下探索;如果不符合解的要求,则退回其父节点。
比较形象来说可以用走迷宫做例子,大多人类一般就是使用回溯法,当走到一条死路,就往回退到前一个岔路,尝试另外一条,直到走出。

Problem

37. Sudoku Solver:Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.’
You may assume that there will be only one unique solution.

Solution

Java Code



public class Solution {
    public void solveSudoku(char[][] board) {
        backtracking(board);


    }

    boolean backtracking(char[][] board){
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; 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(backtracking(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){
        //row
        for(int m = 0; m < 9; m++){
            if( m!=i){
                if( c == board[m][j] ){
                    return false;
                }
            }
        }
        //column
        for(int n = 0; n < 9; n++){
            if( n!=j){
                if( c == board[i][n] ){
                    return false;
                }
            }
        }
        int k_row = i/3;
        int k_column = j/3;
        //sub-box
        for(int m = k_row*3; m < k_row*3+3; m++){
            for(int n = k_column*3; n < k_column*3+3; n++)
            if( m!=i && n!=j){
                if( c == board[m][n] ){
                    return false;
                }
            }
        }
        return true;
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值