Description
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’.
Note:
- The given board contain only digits 1-9 and the character ‘.’.
- You may assume that the given Sudoku puzzle will have a single unique solution.
- The given board size is always 9x9.
解题思路
哎呀这不是我觉得36不用进行很开心的解数独嘛?!
该来的总会来
至少对得起他这个hard
对没错就是对bfs不够熟练
对着一个void想了半天该怎么递归……(是傻子了
还是要用Boolean来递归吧……不然怎么知道这个点影响的后续有没有成功匹配呢
最后查了半天发现错在对九宫格的判断上……直接用 x / 3 作为开始……觉得自己当时没睡醒orz
class Solution {
public static Boolean check(int x, int y, char[][]board){
int i, j;
Set<Character> col, row, block;
col = new HashSet<>();
row = new HashSet<>();
block = new HashSet<>();
for(i = 1; i < 10; i++){
col.add(String.valueOf(i).charAt(0));
row.add(String.valueOf(i).charAt(0));
block.add(String.valueOf(i).charAt(0));
}
for(i = 0; i < 9; i++){
if(col.contains(board[x][i]))
col.remove(board[x][i]);
else if(board[x][i] != '.')
return false;
if(row.contains(board[i][y]))
row.remove(board[i][y]);
else if(board[i][y] != '.')
return false;
}
for(i = x / 3 * 3; i < x / 3 * 3 + 3; i++){
for(j = y / 3 * 3; j < y / 3 * 3 + 3; j++){
if(block.contains(board[i][j]))
block.remove(board[i][j]);
else if(board[i][j] != '.')
return false;
}
}
return true;
}
public void solveSudoku(char[][] board){
solve(board);
}
public Boolean solve(char[][] board) {
int i, j, k;
for(i = 0; i < 9; i++){
for(j = 0; j < 9; j++){
if(board[i][j] == '.'){
for(k = 1; k < 10; k++){
board[i][j] = String.valueOf(k).charAt(0);
if(check(i, j, board) && solve(board))
return true;
else{
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
}
照例摸了下通过里面1ms的大佬代码
看到位运算就知道自己还要继续努力Orz
希望有朝一日自己也能写出位运算的代码