题目传送地址: https://leetcode.cn/problems/sudoku-solver/
好开心,这道题解出来了
代码如下:
public static void solveSudoku(char[][] board) {
Map<String, String> indexMap = initBlank(board);
HashMap<String, Set<Integer>> map = new HashMap<>();
int rowIndex = 0, colIndex = 0;
while (rowIndex < 9 && colIndex < 9) {
if (board[rowIndex][colIndex] != '.') {
if (colIndex < 8) {
colIndex++;
continue;
} else {
rowIndex++;
colIndex = 0;
}
continue;
}
if (fillUnit(board, rowIndex, colIndex, map)) { //如果填充成功
if (colIndex < 8) {
colIndex++;
continue;
} else {
rowIndex++;
colIndex = 0;
}
} else {
map.remove(rowIndex+":"+colIndex);
String lastIndex = indexMap.get(rowIndex + ":" + colIndex);
String[] split = lastIndex.split(":");
int lastRowIndex = Integer.parseInt(split[0]);
int lastColIndex = Integer.parseInt(split[1]);
char c = board[lastRowIndex][lastColIndex];
Set<Integer> set = map.get(lastIndex);
set.remove(c - '0');
map.put(lastIndex, set);
board[lastRowIndex][lastColIndex] = '.';
rowIndex = lastRowIndex;
colIndex = lastColIndex;
continue;
}
}
}
//初始化map以后,我们就可以根据map获取上一个空白位置的坐标
public static Map<String, String> initBlank(char[][] board) {
HashMap<String, String> map = new HashMap<>();
String lastIndex = "";
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
map.put(i + ":" + j, lastIndex);
lastIndex = i + ":" + j;
}
}
}
return map;
}
public static boolean fillUnit(char[][] board, int i, int j, HashMap<String, Set<Integer>> map) {
Set<Integer> set = getList(board, i, j);
Set<Integer> set1 = map.get(i + ":" + j);
if(set1!=null){
set.retainAll(set1);
}
if (set.isEmpty()) {
return false;
}
map.put(i + ":" + j, set);
Iterator<Integer> iterator = set.iterator();
Integer num = iterator.next();
char c = String.valueOf(num).charAt(0);
board[i][j] = c;
return true;
}
public static Set<Integer> getList(char[][] board, int i, int j) {
Set<Integer> set = new HashSet<>();
for (int n = 1; n < 10; n++) {
set.add(n);
}
//行内不能重复
for (int n = 0; n < 9; n++) {
if(board[i][n]!='.'){
set.remove(board[i][n] - '0');
}
}
//列内不能重复
for (int m = 0; m < 9; m++) {
if(board[m][j]!='.'){
set.remove(board[m][j] - '0');
}
}
//九宫格内不能重复
int i1 = i - i % 3;
int j1 = j - j % 3;
for(int m=i1;m<i1+3;m++){
for(int n=j1;n<j1+3;n++){
if(board[m][n]!='.'){
set.remove(board[m][n] - '0');
}
}
}
return set;
}