Sudoku Solver

本文介绍了一种使用回溯法解决数独问题的算法实现。通过递归填充空单元格来寻找唯一解,详细解释了如何存储空位置并验证每一步的有效性。

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

rite 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.


A sudoku puzzle...


...and its solution numbers marked in red.

思路: 典型的回溯法, 和 N-QUEENS 问题一样。 但是为了方便进行下一轮递归, 将所有为空的点的位置存入一个list ,这样方便递归和判断是否结束。

易错点: 在每个block 的判断是否正确时, i 从 0 到 9  刚好在一个block 中。            

 int blockRow = 3 * (x / 3) + i / 3;
            int blockCol = 3 * (y / 3) + i % 3;
            if(board[blockRow][blockCol] == c)
                return false;

public class Solution {
    public void solveSudoku(char[][] board) {
        List<Integer> emptyNodes = new ArrayList<Integer>();
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                if(board[i][j] == '.'){
                    emptyNodes.add(i * 9 + j);
                }
            }
        }
        dfs(board, 0, emptyNodes);
    }
    
    private boolean dfs(char[][] board, int cur, List<Integer> emptyNodes){
        if(cur == emptyNodes.size())
            return true;
        int node = emptyNodes.get(cur);
        int x = node / 9;
        int y = node % 9;
        for(char c = '1'; c <='9'; c++){
            if(isValid(board, x, y, c)){
                board[x][y] = c;
                if(dfs(board, cur + 1, emptyNodes))
                    return true;
                board[x][y] = '.';
            }
        }
        return false;
    }
    
    private boolean isValid(char[][] board, int x, int y, char c){
        for(int i = 0; i < 9; i++){
            if(board[x][i] == c)
                return false;
            if(board[i][y] == c)
                return false;
            int blockRow = 3 * (x / 3) + i / 3;
            int blockCol = 3 * (y / 3) + i % 3;
            if(board[blockRow][blockCol] == c)
                return false;
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值