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

浙公网安备 33010602011771号