kniost

谁怕,一蓑烟雨任平生

0%

LeetCode 37. Sudoku Solver

37. Sudoku Solver

Difficulty: Hard

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 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.

Solution

Language: Java

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {
public void solveSudoku(char[][] board) {
if (board == null || board.length != 9 || board[0].length != 9) {
return;
}
Set<Character>[] rowSet = (Set<Character>[])new HashSet[9];
Set<Character>[] columnSet = (Set<Character>[])new HashSet[9];
Set<Character>[] boxSet = (Set<Character>[])new HashSet[9];
for (int i = 0; i < 9; i++) {
rowSet[i] = new HashSet<>();
columnSet[i] = new HashSet<>();
boxSet[i] = new HashSet<>();
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c != '.') {
rowSet[i].add(c);
columnSet[j].add(c);
boxSet[boxIndex(i, j)].add(c);
}
}
}

solve(board, rowSet, columnSet, boxSet, 0);
}

private int boxIndex(int i, int j) {
return (i / 3) * 3 + j / 3;
}

private boolean solve(char[][] board, Set<Character>[] rowSet, Set<Character>[] columnSet, Set<Character>[] boxSet, int r) {
if (r == 8 && checkValid(rowSet, columnSet, boxSet)) {
return true;
}
for (int i = r; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
int bi = boxIndex(i, j);
if (c == '.') {
for (char s = '1'; s <= '9'; s++) {
if (!rowSet[i].contains(s) && !columnSet[j].contains(s)
&& !boxSet[bi].contains(s)) {
rowSet[i].add(s);
columnSet[j].add(s);
boxSet[bi].add(s);
board[i][j] = s;
if (solve(board, rowSet, columnSet, boxSet, i)) {
return true;
}
board[i][j] = '.';
rowSet[i].remove(s);
columnSet[j].remove(s);
boxSet[bi].remove(s);
}
}
if (board[i][j] == '.') {
return false;
}
}
}
}
return false;
}

private boolean checkValid(Set<Character>[] rowSet, Set<Character>[] columnSet, Set<Character>[] boxSet) {
for (int i = 0; i < 9; i++) {
if (rowSet[i].size() != 9 || columnSet[i].size() != 9 || boxSet[i].size() != 9) {
return false;
}
}
return true;
}
}