Skip to content

Commit 142e569

Browse files
[N-0] refactor 37
1 parent 0c0c602 commit 142e569

File tree

1 file changed

+35
-33
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+35
-33
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,59 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 37. Sudoku Solver
5+
*
46
* Write a program to solve a Sudoku puzzle by filling the empty cells.
57
* Empty cells are indicated by the character '.'.
68
* You may assume that there will be only one unique solution.
7-
* A sudoku puzzle...
8-
* ...and its solution numbers marked in red.
99
*/
1010
public class _37 {
1111

12-
public void solveSudoku(char[][] board) {
13-
if (board == null || board.length == 0) {
14-
return;
12+
public static class Solution1 {
13+
public void solveSudoku(char[][] board) {
14+
if (board == null || board.length == 0) {
15+
return;
16+
}
17+
solve(board);
1518
}
16-
solve(board);
17-
}
1819

19-
private boolean solve(char[][] board) {
20-
for (int i = 0; i < board.length; i++) {
21-
for (int j = 0; j < board[0].length; j++) {
22-
if (board[i][j] == '.') {
23-
for (char c = '1'; c <= '9'; c++) {
24-
//try 1 to 9
25-
if (isValid(board, i, j, c)) {
26-
board[i][j] = c;
20+
private boolean solve(char[][] board) {
21+
for (int i = 0; i < board.length; i++) {
22+
for (int j = 0; j < board[0].length; j++) {
23+
if (board[i][j] == '.') {
24+
for (char c = '1'; c <= '9'; c++) {
25+
//try 1 to 9
26+
if (isValid(board, i, j, c)) {
27+
board[i][j] = c;
2728

28-
if (solve(board)) {
29-
return true;
30-
} else {
31-
board[i][j] = '.';//recover it to be '.'
29+
if (solve(board)) {
30+
return true;
31+
} else {
32+
board[i][j] = '.';//recover it to be '.'
33+
}
3234
}
3335
}
36+
return false;
3437
}
35-
return false;
3638
}
3739
}
40+
return true;
3841
}
39-
return true;
40-
}
4142

42-
private boolean isValid(char[][] board, int row, int col, char c) {
43-
for (int i = 0; i < 9; i++) {
44-
if (board[i][col] != '.' && board[i][col] == c) {
45-
return false;//check row
46-
}
47-
if (board[row][i] != '.' && board[row][i] == c) {
48-
return false;//check column
49-
}
50-
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] != '.' && board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
51-
return false; //check 3*3 block
43+
private boolean isValid(char[][] board, int row, int col, char c) {
44+
for (int i = 0; i < 9; i++) {
45+
if (board[i][col] != '.' && board[i][col] == c) {
46+
return false;//check row
47+
}
48+
if (board[row][i] != '.' && board[row][i] == c) {
49+
return false;//check column
50+
}
51+
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] != '.' && board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
52+
return false; //check 3*3 block
53+
}
5254
}
55+
return true;
5356
}
54-
return true;
5557
}
5658

5759
}

0 commit comments

Comments
 (0)