偶然看到这个题,觉得挺有趣,看到很多用dfs解的,我觉得没有必要,就写了这个。
题目信息:
方格填数
如图,如下的10个格子,填入0~9的数字。要求:连续的两个数字不能相邻。hu
(左右、上下、对角都算相邻)一共有多少种可能的填数方案?
请填写表示方案数目的整数。
judge()方法来判断此处填数是否符合要求,find()方法用来递归填数,整体方法类似于八皇后的解法,如果这个位置不能填则说明前面填的数字不合适,向前回溯。如果想看具体每一步的结果,由于java中没有system(“pause”),可以利用scanner来达到同样的效果,这是我本次最大的收获。
public class Test3 {
//用来填数
private static int [] [] table = new int [3] [4];
//用来判断某个格子是否填了数
private static boolean [] [] map = new boolean [] [] {{true,true,true,true},{true,true,true,true},{true,true,true,true}};
//分别表示左、左上、上、右上、右、右下、下、左下八个方向
private static int [] [] around = new int [][] {{0,-1},{-1,-1},{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1}};
//符合条件的填法
private static int result = 0;
static {
map[0][0] = false;
map[2][3] = false;
}
public static void main(String[] args) {
find(0);
System.out.println(result);
}
//k代表当前正要填的数字
public static void find(int k) {
if(k == 10) {
//用来查看填数的结果
/*for(int i = 0; i < 3 ;i++) {
for(int j = 0 ; j < 4;j++) {
if((i == 0 && j==0) || (i == 2 && j == 3)) {
System.out.print("x ");
continue;
}
System.out.print(visit[i][j] +" ");
}
System.out.println("");
}
System.out.println("-----------------------------");*/
result++;
}
for(int i = 0 ; i < 3; i++) {
for(int j = 0 ; j < 4;j++) {
if(map[i][j]) {
if(judge(i, j, k)) {
table[i][j] = k;
map[i][j] = false;
find(k+1);
map[i][j] = true;
}
}
}
}
}
//判断能不能往这个格子里填
public static boolean judge(int i,int j,int k) {
int x,y;
for(int loop =0 ;loop < 8;loop++) {
x = i + around[loop][0];
y = j + around[loop][1];
if(x < 0 || x > 2 || y < 0 || y > 3 ||(x == 0 && y == 0) || (x == 2 && y ==3)){
continue;
}
if(!map[x][y] && Math.abs(k - table[x][y]) ==1) {
return false;
}
//System.out.println("("+x+","+y+")");
}
return true;
}
}