37. 解数独

该博客介绍了一种优化的数独求解算法,通过使用位运算来存储每行、每列和每个宫格中已出现的数字,从而减少空间复杂度。这种方法将原本需要9个元素的数组降低到一个9位整数,提高了算法效率。博主还详细解释了递归回溯在解题过程中的应用,使得数独求解更为高效。

37. 解数独

class Solution {
    boolean[][] row = new boolean[9][9];
    boolean[][] colomn = new boolean[9][9];
    boolean[][][] block = new boolean[3][3][9];
    char[][] res = new char[9][9];
    public void solveSudoku(char[][] board) {

        for(int i = 0; i < 9;i++){
            for(int j = 0;j < 9;j++){
                if(board[i][j] != '.'){
                    int digit = board[i][j] - '0' - 1;
                    row[i][digit] = colomn[j][digit] = block[i/3][j/3][digit] = true;
                }
            }
        }
        backtracking(board,0,0);
        for(int i = 0; i < 9;i++){
            for(int j = 0; j < 9;j++){
                board[i][j] = res[i][j];
            }
        }
        
    }
    public void backtracking(char[][] board, int x, int y){
        if(x == 9){
            for(int i = 0; i < 9;i++){
                for(int j = 0; j < 9;j++){
                    res[i][j] = board[i][j];
                }
            }
            return;
        }
        
        if(board[x][y] != '.'){
            if(y == 8) backtracking(board,x + 1,0);
            else backtracking(board,x,y + 1);
        }else{
            for(int j = 0;j < 9;j++){
                char cur = transfer(j + 1);
                  
                if(!row[x][j] && !colomn[y][j] && !block[x/3][y/3][j]){
                    board[x][y] = cur;
                    row[x][j] = colomn[y][j] = block[x/3][y/3][j] = true;
                    if(y == 8) backtracking(board,x + 1,0);
                    else backtracking(board,x,y + 1);
                    row[x][j] = colomn[y][j] = block[x/3][y/3][j] = false;
                    board[x][y] = '.';
                }
            }
        }
    }
    public char transfer(int n){
        return (char)(n + '0');
    }
}

用row和colomn记录每行每列出现的数字,用block记录每个block记录出现过的数字,递归回溯即可。
还有更快的,用位运算,把本来需要长度为9的数组储存出现过的数字,用一个9位长度的整数储存数据。等于降了一个维度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值