Link: https://oj.leetcode.com/problems/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.
A sudoku puzzle...
(Figure: Leetcode)My thought: I can create three hashsets, one rowSet to check duplicate for each row, one colSet to check duplicates for each col, and one hashSet to check duplicates in each 3*3 square. However, for each row/col/square, how do Irandomlyassign numbers available?
My original code:
public class Solution {
public void solveSudoku(char[][] board) {
HashSet<Integer> rowSet = new HashSet<Integer>();
for(int i = 1; i < 10; i++){
rowSet.add(i);
}
HashSet <Integer> colSet = new HashSet<Integer>();
for(int i = 1; i < 10; i++){
colSet.add(i);
}
dfs(board, rowSet, colSet, 0, 0);
}
public void dfs(char[][] board, HashSet<Integer> rowSet, HashSet<Integer> rowSet){
}
}
Correct Answer:
public 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] == '.'){//if it's an empty cell
for(int k = 1; k < 10; k++){//fill in a bumber between [1, 9]
board[i][j] = (char) (k + '0');//k + ASCII of 0 = ASCII of k
if(isValid(board, i, j) && solve(board)){
return true;
}
board[i][j] = '.';
}
//tried 1-9, but "solve(board)" all = F, go back to previous cell and change it
return false;
}
}
}
return true;
}
public boolean isValid (char[][] board, int row, int col){
//check row
for(int k = 0; k < 9; k++){
if(k!=col && board[row][k] == board[row][col]) return false;
}
//check col
for(int k = 0; k < 9; k++){
if(k!=row && board[k][col] == board[row][col]) return false;
}
//check 3*3 squares
int a = row/3*3;//the start row index for each 3*3 square
int b = col/3*3;//the start col index for each 3*3 square
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(a+i == row && b+j == col) continue;
if(board[row][col] == board[a+i][b+j]){
return false;
}
}
}
return true;
}
}
相关题目: N-Queens
Note in N-Queens, we check valid before placing a Queen. Here, we place a number before checking validation.