Skip to content

Commit f4883ad

Browse files
committed
37
1 parent f491940 commit f4883ad

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,5 @@
3737
* [34. Find First and Last Position of Element in Sorted Array](leetCode-34-Find-First-and-Last-Position-of-Element-in-Sorted-Array.md)
3838
* [35. Search Insert Position](leetCode-35-Search-Insert-Position.md)
3939
* [36. Valid Sudoku](leetCode-36-Valid-Sudoku.md)
40+
* [37. Sudoku Solver](leetCode-37-Sudoku-Solver.md)
4041
* [79. Word Search](leetCode-79-Word-Search.md)

leetCode-37-Sudoku-Solver.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# 题目描述(困难难度)
2+
3+
![](https://windliang.oss-cn-beijing.aliyuncs.com/37.png)
4+
5+
给定一个数独棋盘,输出它的一个解。
6+
7+
# 解法一 回溯法
8+
9+
从上到下,从左到右遍历每个空位置。在第一个位置,随便填一个可以填的数字,再在第二个位置填一个可以填的数字,一直执行下去直到最后一个位置。期间如果出现没有数字可以填的话,就回退到上一个位置,换一下数字,再向后进行下去。
10+
11+
```java
12+
public void solveSudoku(char[][] board) {
13+
solver(board);
14+
}
15+
private boolean solver(char[][] board) {
16+
for (int i = 0; i < 9; i++) {
17+
for (int j = 0; j < 9; j++) {
18+
if (board[i][j] == '.') {
19+
char count = '1';
20+
while (count <= '9') {
21+
if (isValid(i, j, board, count)) {
22+
board[i][j] = count;
23+
if (solver(board)) {
24+
return true;
25+
} else {
26+
//下一个位置没有数字,就还原,然后当前位置尝试新的数
27+
board[i][j] = '.';
28+
}
29+
}
30+
count++;
31+
}
32+
return false;
33+
}
34+
}
35+
}
36+
return true;
37+
}
38+
39+
private boolean isValid(int row, int col, char[][] board, char c) {
40+
for (int i = 0; i < 9; i++) {
41+
if (board[row][i] == c) {
42+
return false;
43+
}
44+
}
45+
46+
for (int i = 0; i < 9; i++) {
47+
if (board[i][col] == c) {
48+
return false;
49+
}
50+
}
51+
52+
int start_row = row / 3 * 3;
53+
int start_col = col / 3 * 3;
54+
for (int i = 0; i < 3; i++) {
55+
for (int j = 0; j < 3; j++) {
56+
if (board[start_row + i][start_col + j] == c) {
57+
return false;
58+
}
59+
}
60+
61+
}
62+
return true;
63+
}
64+
```
65+
66+
时间复杂度:
67+
68+
空间复杂度:O(1)。
69+
70+
#
71+
72+
回溯法一个很典型的应用了。

0 commit comments

Comments
 (0)