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

LeetCode 37. Sudoku Solver_第1张图片

A sudoku puzzle...

LeetCode 37. Sudoku Solver_第2张图片

...and its solution numbers marked in red.

题意:求解一个数独,的完整解。

public void solveSudoku(char[][] board) {
        solve(board);
    }
    private boolean solve(char[][] board){
         for(int row = 0;row<9;row++){
             for(int col = 0;col<9;col++){
                 if(board[row][col] ==  '.'){
                     for(char i = '1';i<='9';i++){
                         board[row][col] = i;
                         if(isValid(board,row,col) && solve(board))
                            return true;
                         board[row][col] = '.';
                     }
                     return false;
                 }
             }
         }
         return true;
    }
    private boolean isValid(char[][] board,int row,int col){
        for(int i = 0;i<9;i++){
            if(i!=col && board[row][i] == board[row][col])
                return false;
        }
        for(int i = 0;i<9;i++){
            if(i!=row && board[i][col] == board[row][col])
                return false;
        }
        int beginRow = 3*(row/3);
        int beginCol = 3*(col/3);
        for(int i = beginRow;i

你可能感兴趣的:(LeetCode 37. Sudoku Solver)