37 Sudoku Solver

1. Question

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.

2. Implementation

(1) Backtracking
1
class Solution {
2
public void solveSudoku(char[][] board) {
3
if (board == null || board.length == 0) {
4
return;
5
}
6
recSolveSudoku(board);
7
}
8
9
public boolean recSolveSudoku(char[][] board) {
10
for (int i = 0; i < board.length; i++) {
11
for (int j = 0; j < board[0].length; j++) {
12
if (board[i][j] == '.') {
13
for (char c = '1'; c <= '9'; c++) {
14
if (isValid(board, i, j, c)) {
15
board[i][j] = c;
16
17
if (recSolveSudoku(board)) {
18
return true;
19
}
20
21
board[i][j] = '.';
22
}
23
}
24
return false;
25
}
26
}
27
}
28
return true;
29
}
30
31
public boolean isValid(char[][] board, int row, int col, char num) {
32
for (int i = 0; i < 9; i++) {
33
if (board[i][col] == num || board[row][i] == num) {
34
return false;
35
}
36
37
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num) {
38
return false;
39
}
40
}
41
return true;
42
}
43
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(9^n),n是board为空格的个数, 空间复杂度O(n), 递归的深度最多为n