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.
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
.
题意:
解数独
Solution1: Backtracking
code
1 class Solution { 2 public void solveSudoku(char[][] board) { 3 if (board == null || board.length != 9 || board[0].length != 9) return; 4 boolean tmp = helper(board, 0, 0); 5 } 6 7 public boolean helper(char[][] board, int row, int col) { 8 if (board == null || board.length != 9 || board[0].length != 9) return false; 9 10 while (row < 9 && col < 9) { 11 if (board[row][col] == '.') break; // find the 1st empty spot 12 if (col == 8) {// 说明要换行了 13 col = 0; 14 row++; 15 } else { 16 col++; 17 } 18 } 19 if (row >= 9) return true; 20 int nextRow = row + col / 8; 21 int nextCol = (col + 1) % 9; 22 23 for (int num = 1; num <= 9; num++) { 24 if (isValid(board, row, col, num)) { // 该num在行,列,box都没出现过 25 board[row][col] = (char) (num + '0'); // 试着将num填入cur spot 26 boolean result = helper(board, nextRow, nextCol); // 递归调用,下一个 27 if (result) return true; 28 board[row][col] = '.'; // 如果num在cur spot不合法,回溯。 还原。 29 } 30 } 31 return false; 32 } 33 34 // check num is valid at such spot 35 // which means in cur row, col or box, this num hasn't appeared before 36 public boolean isValid(char[][] board, int row, int col, int num) { 37 // check row 38 for (int i = 0; i < 9; i++) { 39 if (board[row][i] == num + '0') 40 return false; 41 } 42 //check col 43 for (int i = 0; i < 9; i++) { 44 if (board[i][col] == num + '0') 45 return false; 46 } 47 //check box 48 int rowoff = (row / 3) * 3; 49 int coloff = (col / 3) * 3; 50 for (int i = 0; i < 3; i++) { 51 for (int j = 0; j < 3; j++) { 52 if (board[rowoff + i][coloff + j] == num + '0') return false; 53 } 54 } 55 return true; 56 } 57 }