[LeetCode] Problem 37 - Sudoku Solver

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 ‘.’.

Zv4Ey4.png

A sudoku puzzle…

ZvLcB8.png

…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.

Code

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
private boolean[][] row = new boolean[9][9];
private boolean[][] col = new boolean[9][9];
private boolean[][] cell = new boolean[9][9];

public void solveSudoku(char[][] board) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.')
continue;

int num = board[i][j] - '1';
row[i][num] = true;
col[j][num] = true;
cell[(i / 3) * 3 + (j / 3)][num] = true;
}
}

helper(board, 0);
}

private boolean helper(char[][] board, int pos) {
if (pos == 81)
return true;

int x = pos / 9;
int y = pos % 9;

if (board[x][y] != '.')
return helper(board, pos + 1);

for (int k = 0; k < 9; k++) {
int p = (x / 3) * 3 + (y / 3);

if (!row[x][k] && !col[y][k] && !cell[p][k]) {
board[x][y] = (char) (k + 1 + '0');
row[x][k] = true;
col[y][k] = true;
cell[p][k] = true;

if (helper(board, pos + 1))
return true;

board[x][y] = '.';
row[x][k] = false;
col[y][k] = false;
cell[p][k] = false;
}
}

return false;
}