37. Sudoku Solver

rite 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.
Empty cells are indicated by the character '.'.


A sudoku puzzle...


...and its solution numbers marked in red.

Note:

The given board contain only digits 1-9 and the character '.'.
You may assume that the given Sudoku puzzle will have a single unique solution.
The given board size is always 9x9.
Seen this question in a real interview before?  YesNo
Difficulty:Hard
Total Accepted:100.6K
Total Submissions:302.4K
Contributor:LeetCode
Subscribe to see which companies asked this question.

Related Topics 
Hash TableBacktracking
Similar Questions 
Valid Sudoku
Java	





class Solution {
    public void solveSudoku(char[][] board) {
        
    }
}
1
public class Solution {
2
    public void solveSudoku(char[][] board) {
3
        if(board == null || board.length == 0)
4
            return;
5
        solve(board);
6
    }
7
    
8
    public boolean solve(char[][] board){
9
        for(int i = 0; i < board.length; i++){
10
            for(int j = 0; j < board[0].length; j++){
11
                if(board[i][j] == '.'){
12
                    for(char c = '1'; c <= '9'; c++){//trial. Try 1 through 9
13
                        if(isValid(board, i, j, c)){
14
                            board[i][j] = c; //Put c for this cell
15
                            
16
                            if(solve(board))
17
                                return true; //If it's the solution return true
18
                            else
19
                                board[i][j] = '.'; //Otherwise go back
20
                        }
21
                    }
22
                    
23
                    return false;
24
                }
25
            }
26
        }
27
        return true;
28
    }
29
    
30
    private boolean isValid(char[][] board, int row, int col, char c){
31
        for(int i = 0; i < 9; i++) {
32
            if(board[i][col] != '.' && board[i][col] == c) return false; //check row
33
            if(board[row][i] != '.' && board[row][i] == c) return false; //check column
34
            if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' && 
35
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block
36
        }
37
        return true;
38
    }

 

点赞