classSolution{ Set<Character>[] rows = new HashSet[9]; Set<Character>[] cols = new HashSet[9]; Set<Character>[] boxes = new HashSet[9];
publicvoidsolveSudoku(char[][] board){ for (int i = 0; i < 9; i++) { rows[i] = new HashSet<Character>(); cols[i] = new HashSet<Character>(); boxes[i] = new HashSet<Character>(); }
for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] != '.') { rows[i].add(board[i][j]); cols[j].add(board[i][j]); boxes[(i / 3) * 3 + j / 3].add(board[i][j]); } } }
backtracking(board, 0, 0, rows, cols, boxes); }
privatebooleanbacktracking(char[][] board, int i, int j, Set<Character>[] rows, Set<Character>[] cols, Set<Character>[] boxes){ // 到达最后一列,开始对下一行进行回溯 if (j == 9) { return backtracking(board, i + 1, 0, rows, cols, boxes); }
// 完成最后一行,结束,说明找到解了 if (i == 9) { returntrue; }
int box_id = (i / 3) * 3 + j / 3; if (board[i][j] != '.') { return backtracking(board, i, j + 1, rows, cols, boxes); } else { for (char c = '1'; c <= '9'; c++) { // 检查当前这个值是否valid if (!rows[i].contains(c) && !cols[j].contains(c) && !boxes[box_id].contains(c)) { board[i][j] = c; rows[i].add(c); cols[j].add(c); boxes[box_id].add(c); if (!backtracking(board, i, j + 1, rows, cols, boxes)) { // 回溯 rows[i].remove(c); cols[j].remove(c); boxes[box_id].remove(c); board[i][j] = '.'; continue; } else { returntrue; } } } returnfalse; }
booleanbacktrack(char[][] board, int i, int j){ int m = 9, n = 9; if (j == n) { // 穷举到最后一列的话就换到下一行重新开始。 return backtrack(board, i + 1, 0); } if (i == m) { // 找到一个可行解,触发 base case returntrue; }
if (board[i][j] != '.') { // 如果有预设数字,不用我们穷举 return backtrack(board, i, j + 1); }
for (char ch = '1'; ch <= '9'; ch++) { // 如果遇到不合法的数字,就跳过 if (!isValid(board, i, j, ch)) continue;