自己写的不知道哪里出问题了,贴一个类似的评论区的代码,逻辑还是明显比自己的清晰好多。
在自己代码基础上稍微改了改,用map加set存,
代码来源:
作者:Angus-Liu
链接:
https://leetcode-cn.com/problems/sudoku-solver/comments/
class Solution {
public void solveSudoku(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0){
return;
}
int row = board.length;
int col = board[0].length;
HashMap<Integer,HashSet<Integer>> rowMap = new HashMap<>();
for (int i = 0; i < 9; i++) {
rowMap.put(i,new HashSet<>());
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != '.'){
rowMap.get(i).add(board[i][j] - '0');
}
}
}
HashMap<Integer,HashSet<Integer>> colMap = new HashMap<>();
for (int i = 0; i < 9; i++) {
colMap.put(i,new HashSet<>());
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != '.') {
colMap.get(j).add(board[i][j] - '0');
}
}
}
HashMap<Integer,HashSet<Integer>> blockMap = new HashMap<>();
for (int i = 0; i < 9; i++) {
blockMap.put(i,new HashSet<>());
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] != '.'){
blockMap.get((i / 3) * 3 + (j / 3)).add(board[i][j] - '0');
}
}
}
dfsSolveSudoku(board,rowMap,colMap,blockMap,0,0);
}
private boolean dfsSolveSudoku(char[][] board, HashMap<Integer, HashSet<Integer>> rowMap, HashMap<Integer, HashSet<Integer>> colMap, HashMap<Integer, HashSet<Integer>> blockMap, int x, int y) {
while (board[x][y] != '.') {
if (++y >= 9) {
x++;
y = 0;
}
if (x >= 9) {
return true;
}
}
for (int i = 1; i < 10; i++) {
if (!rowMap.get(x).contains(i) && !colMap.get(y).contains(i) && !blockMap.get((x / 3) * 3 + y / 3).contains(i)){
board[x][y] = (char)('0' + i);
rowMap.get(x).add(i);
colMap.get(y).add(i);
blockMap.get((x / 3) * 3 + y / 3).add(i);
if (dfsSolveSudoku(board,rowMap,colMap,blockMap,x,y)){
return true;
} else {
board[x][y] = '.';
rowMap.get(x).remove(i);
colMap.get(y).remove(i);
blockMap.get((x / 3) * 3 + y / 3).remove(i);
}
}
}
return false;
}
}