关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers
LeetCode题目:36. 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 '.'
.
A partially filled sudoku which is valid.
Note:
- A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
class Solution {
public boolean isValidSudoku(char[][] board) {
int n = board.length;
for(int i = 0; i < n; i++) {
Set<Character> rows = new HashSet<Character>();
Set<Character> columns = new HashSet<Character>();
Set<Character> cubes = new HashSet<Character>();
for(int j = 0; j < n; j++) {
if(board[i][j] != '.') {
// check each row
if(rows.contains(board[i][j])) {
return false;
}
else {
rows.add(board[i][j]);
}
}
if(board[j][i] != '.') {
// check each column
if(columns.contains(board[j][i])) {
return false;
}
else {
columns.add(board[j][i]);
}
}
int rowIdx = 3 * (i / 3);
int columnIdx = 3 * (i % 3);
if(board[rowIdx + j / 3][columnIdx + j % 3] != '.') {
// check each cube
if(cubes.contains(board[rowIdx + j / 3][columnIdx + j % 3])) {
return false;
}
else {
cubes.add(board[rowIdx + j / 3][columnIdx + j % 3]);
}
}
}
}
return true;
}
}
LeetCode题目:37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'
.
You may assume that there will be only one unique solution.
class Solution {
public void solveSudoku(char[][] board) {
if(board == null || board.length == 0 || board[0].length == 0) {
return;
}
solve(board);
}
public boolean solve(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(solve(board)) {
return true;
}
else {
// 回溯 backtracking
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
// 把(row, col)位置设为c,判断是不是合法的数独
private boolean isValid(char[][] board, int row, int col, char c){
for(int i = 0; i < 9; i++) {
// 检查第col列,不能有重复的c
if(board[i][col] != '.' && board[i][col] == c) {
return false;
}
// 检查第row行,不能有重复的c
if(board[row][i] != '.' && board[row][i] == c) {
return false;
}
// 检查对应的cube,不能有重复的c
if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' &&
board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) {
return false;
}
}
return true;
}
}