-
Notifications
You must be signed in to change notification settings - Fork 2
/
37.sudoku-solver.java
56 lines (49 loc) · 1.5 KB
/
37.sudoku-solver.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
/*
* @lc app=leetcode id=37 lang=java
*
* [37] Sudoku Solver
*/
// @lc code=start
class Solution {
public void solveSudoku(char[][] board) {
if (board.length == 0 || board == null) {
return;
}
boolean result = helper(board);
}
public boolean helper(char[][] board) {
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if (board[i][j] == '.') {
for (char c = '1'; c <= '9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (helper(board)) {
return true;
}
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
public boolean isValid(char[][] board, int row, int column, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][column] != '.' && board[i][column] == c) {
return false;
}
if (board[row][i] != '.' && board[row][i] == c) {
return false;
}
char temp = board[(row / 3) * 3 + i / 3][(column / 3) * 3 + i % 3];
if (temp != '.' && temp == c) {
return false;
}
}
return true;
}
}
// @lc code=end