Leetcode no. 37

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.


A sudoku puzzle...


...and its solution numbers marked in red.

public class Solution {
    public void solveSudoku(char[][] board) {
        solve(board, 0);
    }
    private boolean solve(char[][] b, int pos){
        int row= pos/9;
        int col= pos%9;
        int[] box= {row/3, col/3};
        if (pos== 81)
            return true;
        if (b[row][col] != '.'){
            if (solve(b, pos+1))
                return true;
        }
        else{
            for (int i = 1; i <= 9; i++) {
                String s= String.valueOf(i);
                char ch= s.charAt(0);
                if (CheckRow(b, row, ch)
                        && CheckColumn(b, col, ch)
                        && CheckBox(b, box, ch)){
                    b[row][col]= ch;
                    if (solve(b, pos+1))
                        return true;
                    b[row][col]= '.';
                }
            }
        }
        return false;
    }

    public boolean CheckRow(char[][] b, int row, char num) {
        for (int i = 0; i < 9; i++) {
            if (b[row][i] == num)
                return false;
        }
        return true;
    }
    public boolean CheckColumn(char[][] b, int column, char num) {
        for (int i = 0; i < 9; i++) {
            if (b[i][column] == num)
                return false;
        }
        return true;
    }
    public boolean CheckBox(char[][] b, int[] boxNum, char num){
        for (int row = 0; row < 3; row++) {
            for (int column = 0; column < 3; column++) {
                int currentRow= row+ 3*boxNum[0];
                int currentColumn= column+ 3*boxNum[1];
                if (b[currentRow][currentColumn] == num)
                    return false;
            }
        }
        return true;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值