数独
样例输入:
* 2 6 * * * * * *
* * * 5 * 2 * * 4
* * * 1 * * * * 7
* 3 * * 2 * 1 8 *
* * * 3 * 9 * * *
* 5 4 * 1 * * 7 *
5 * * * * 1 * * *
6 * * 9 * 7 * * *
* * * * * * 7 5 *
思路
从第一个点(本题是0,0)开始深搜,先写边界条件。当越界时进行处理;当找到时输出并设置标记退出DFS。
其他情况(可以填数)从1--9开始遍历填数,并检查横、竖、小方格是否有重复的数字。符合条件则填上去然后从下一个点开始继续搜索,搜完后没有结束则取消填数,进行其他填数的尝试
import java.util.*;
import java.math.*;
public class Main {
static int[][] map = new int[9][9];
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
boolean f = false;
int x = 0;
int y = 0;
for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
String c = cin.next();
if(c.equals("*")) {
if(!f) {
f = true;
x = i;
y = j;
}
map[i][j] = 0;
}
else map[i][j] = Integer.valueOf(c);
}
}
dfs(0, 0);
}
static boolean flag = false;
private static void dfs(int x,int y) {
if(flag) return ;
if(y == 9) {
x++; y = 0;
}
if(x == 9) {
flag = true;
for(int i=0; i<9; i++) {
for(int j=0; j<9; j++) {
System.out.print(map[i][j]+" ");
}
System.out.println();
}
return ;
}
if(map[x][y] == 0) {
for(int i=1; i<=9; i++) {
if(check(x, y, i)) {
map[x][y] = i;
dfs(x, y + 1);
map[x][y] = 0;
}
}
}
else {
dfs(x, y + 1);
}
}
static boolean[] vis = new boolean[10];
private static boolean check(int x, int y, int val) {
Arrays.fill(vis, false);
for(int i=0; i<9; i++) {
int t = map[x][i];
if(t != 0) vis[t] = true;
t = map[i][y];
if(t != 0) vis[t] = true;
}
int row = x/3*3;
int col = y/3*3;
for(int i=row; i<=row+2; i++) {
for(int j=col; j<=col+2; j++) {
int t = map[i][j];
if(t != 0) vis[t] = true;
}
}
if(vis[val] == true) return false;
return true;
}
}