Sudoku Solver

题目要求

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

题解

class Solution {
    public void solveSudoku(char[][] board) {
        backTraceing(board);
    }
    private boolean backTraceing(char[][] board){
        for(int i = 0; i < board.length;i++){
            for(int j = 0; j < board.length;j++){
                if(board[i][j] < '0' || board[i][j] > '9'){
                    for(char k = '1'; k <= '9'; k++){
                        board[i][j] = k;
                        if(isTrue(board,i,j)){
                            if(!backTraceing(board)){
                                board[i][j] = '.';
                            }else{
                                return true;
                            }
                        }else{
                            board[i][j] = '.';
                        }
                    }
                    return false;
                }
            }
        }
        return true;
    }
    private boolean isTrue(char[][] board,int row,int column){
        return isVailed(board,row,column,true) && isVailed(board,row,column,false) && isVailed(board,row,column);
    }
    
    private boolean isVailed(char[][] board,int row,int column,boolean isRow){
        boolean[] marked = new boolean[board.length + 1];
        for(int i = 0; i < board.length; i++){
            int current = -2;
                if(isRow){
                    current = board[row][i] - '0';
                }
                else{
                    current = board[i][column] - '0';
                }
                current = current > 0 ? current : 0;
                if(current > 0 && marked[current]) return false;
                marked[current] = true;
        }
        return true;
    }
    
    private boolean isVailed(char[][] board,int row,int column){
        row = (row / 3) * 3;
        column = (column / 3) * 3;
        boolean[] marked = new boolean[board.length + 1];
        for(int i = row; i < row + 3;i++){
            for(int j = column; j < column + 3;j++){
                int current = board[i][j] - '0';
                current = current > 0 ? current : 0;
                if(current > 0 && marked[current]) return false;
                marked[current] = true;
            }
        }
        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值