# Valid Sudoku leetcode

lpy1990

## Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The
Rules.

The Sudoku board could be partially filled, where empty cells are
filled with the character '.'.

### 回溯法

#### 代码

``````public void solveSudoku(char[][] board) {
if (board == null || board.length < 9 || board[0].length < 9) {
return;
}
helper(board, 0, 0);
}
public boolean helper(char[][] board, int m, int n) {
if (n >= 9) {
return helper(board, m + 1, 0);
}
if (m == 9) {
return true;
}
if (board[m][n] == '.') {
for (char i = '1'; i <= '9'; i++) {
board[m][n] = i;
if (isValid(board, m, n)) {
if (helper(board, m, n + 1)) {
return true;
}
}
board[m][n] = '.';
}
} else {
return helper(board, m, n+ 1);
}
return false;
}
public boolean isValid(char[][] board, int m, int n) {
for (int i = 0; i < 9; i++) {
if (i != m && board[i][n] == board[m][n]) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (i != n && board[m][i] == board[m][n]) {
return false;
}
}
for (int i = m / 3 * 3; i< m / 3 * 3 + 3; i++) {
for (int j = n /3 * 3; j < n / 3 *3 + 3; j++) {
if (i != m && j != n && board[i][j] == board[m][n]) {
return false;
}
}
}
return true;
}``````

26 声望
10 粉丝
0 条评论