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 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
A sudoku puzzle...
...and its solution numbers marked in red.
如果当前位置是空,则尝试1到9中所有的数字,如果对于1到9中的某些数字,当前是合法的,则继续尝试下一个位置(调用自身)。
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 } 35 for(int i = 3*(row/3);i<3*(row/3+1);i++) 36 for(int j = 3*(col/3);j<3*(col/3+1);j++) 37 if(board[i][j] != '.' && board[i][j] == c) return false; //check 3*3 block 38 39 return true; 40 } 41 }