AcWing 1613. 数独简单版(注释)
原题链接
简单
作者:
叶忖
,
2021-03-05 15:55:42
,
所有人可见
,
阅读 394
Java 代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
private static int N = 10;
private static char[][] g = new char[N][N];
private static boolean[][] row = new boolean[N][N], col = new boolean[N][N];
private static boolean[][][] cell = new boolean[N][N][N];
private static BufferedReader reader;
private static PrintWriter writer;
private static boolean dfs(int x, int y) {
if (y == 9) {
x ++;
y = 0;
}
if (x == 9) {
for (int i = 0; i < 9; i ++) writer.println(g[i]);
writer.flush();
return true;
}
// 当前不是空搜索下一个
if (g[x][y] != '.') return dfs(x, y + 1);
// 遍历数独中的数字1-9
for (int i = 1; i <= 9; i ++) {
if (!row[x][i] && !col[y][i] && !cell[x / 3][y / 3][i]) {
g[x][y] = (char) (i + '0');
row[x][i] = col[y][i] = cell[x / 3][y / 3][i] = true;
if (dfs(x, y + 1) == true) return true; // 剪枝
// 还原
row[x][i] = col[y][i] = cell[x / 3][y / 3][i]= false;
g[x][y] = '.';
}
}
return false;
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
for (int i = 0; i < 9; i ++) {
g[i] = reader.readLine().toCharArray();
}
reader.close();
for (int i = 0; i < 9; i ++) {
for (int j = 0; j < 9; j ++) {
if (g[i][j] != '.') {
int t = g[i][j] - '0'; // 转换坐标
row[i][t] = col[j][t] = cell[i / 3][j / 3][t] = true;
}
}
}
dfs(0, 0);
writer.flush();
writer.close();
}
}