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.

img1

A sudoku puzzle…
img2

…and its solution numbers marked in red.

解法1: DFS, O(9^N)

N是空格子的总数
就是一个比较直接的dfs的题。对于每一个空格子尝试从1到9,然后检查是否是valid,如果是则继续,如果不是就填回原来的数字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public void solveSudoku(char[][] board) {
if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) {
return;
}
solve(board);
}
private boolean solve(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.') {
// fill up 1 to 9
for (char ch = '1'; ch <= '9'; ch++) {
if (isValid(board, i, j, ch)) {
board[i][j] = ch;
boolean next = solve(board);
if (next) {
return true;
} else {
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int row, int col, char ch) {
for (int i = 0; i < 9; i++) {
if (board[i][col] != '.' && board[i][col] == ch) return false;
if (board[row][i] != '.' && board[row][i] == ch) return false;
// check the small matrix
int matrixRow = (row / 3) * 3 + i / 3;
int matrixCol = (col / 3) * 3 + i % 3;
if (board[matrixRow][matrixCol] != '.' && board[matrixRow][matrixCol] == ch) return false;
}
return true;
}
}