mirror of
https://github.com/arkorty/LeetCode.git
synced 2026-03-17 16:51:46 +00:00
Refactor Hard/sudoku-solver/Solution.java
This commit is contained in:
@@ -1,57 +1,68 @@
|
|||||||
class Solution {
|
class Solution {
|
||||||
char[][] BOARD;
|
char[][] Board;
|
||||||
|
|
||||||
boolean isValid(int row, int col, char num) {
|
boolean isValid(int row, int col, char num) {
|
||||||
for (int i = 0; i < 9; i++) {
|
for (int i = 0; i < 9; i++) {
|
||||||
if (BOARD[i][col] == num)
|
if (Board[i][col] == num) {
|
||||||
return false;
|
return false;
|
||||||
if (BOARD[row][i] == num)
|
}
|
||||||
|
|
||||||
|
if (Board[row][i] == num) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
row = row - row % 3;
|
row = row - row % 3;
|
||||||
col = col - col % 3;
|
col = col - col % 3;
|
||||||
for (int i = 0; i < 3; i++)
|
for (int i = 0; i < 3; i++) {
|
||||||
for (int j = 0; j < 3; j++)
|
for (int j = 0; j < 3; j++) {
|
||||||
if (BOARD[i + row][j + col] == num)
|
if (Board[i + row][j + col] == num) {
|
||||||
return false;
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int[] nextEmpty() {
|
int[] nextEmpty() {
|
||||||
for (int i = 0; i < 9; i++)
|
for (int i = 0; i < 9; i++) {
|
||||||
for (int j = 0; j < 9; j++)
|
for (int j = 0; j < 9; j++) {
|
||||||
if (BOARD[i][j] == '.')
|
if (Board[i][j] == '.') {
|
||||||
return new int[] { i, j };
|
return new int[] { i, j };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new int[] { -1, -1 };
|
return new int[] { -1, -1 };
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean solver() {
|
boolean solver() {
|
||||||
int[] tmp = nextEmpty();
|
int[] tmp = nextEmpty();
|
||||||
if (tmp[0] == -1)
|
if (tmp[0] == -1) {
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
int row = tmp[0];
|
int row = tmp[0];
|
||||||
int col = tmp[1];
|
int col = tmp[1];
|
||||||
|
|
||||||
for (int i = 1; i <= 9; i++) {
|
for (int i = 1; i <= 9; i++) {
|
||||||
if (isValid(row, col, (char) (48 + i))) {
|
if (isValid(row, col, (char) (48 + i))) {
|
||||||
BOARD[row][col] = (char) (48 + i);
|
Board[row][col] = (char) (48 + i);
|
||||||
|
|
||||||
if (solver())
|
if (solver()) {
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
BOARD[row][col] = '.';
|
Board[row][col] = '.';
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void solveSudoku(char[][] board) {
|
public void solveSudoku(char[][] board) {
|
||||||
BOARD = board;
|
Board = board;
|
||||||
solver();
|
solver();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user