題目:
填入0~9的數字。要求:連續的兩個數字不能相鄰。(左右、上下、對角都算相鄰)一共有多少種可能的填數方案?
這題應該用回溯法解決,設置一個二維數組,爲了方便後面判斷某一個格子中的數字是否會和其他數字相連,這題在設置二維數組的時候最好給這個方格四周再加上一排,並且設置所有的方格中的數字爲-9,即設置一個長爲6,寬爲5的二維數組,然後從[1][2]的位置開始搜索,先處理每一排,一排處理完成之後處理下一排,直到處理到[3][4]的位置的時候就得到了一種方案,方案數目加1,代碼如下:
import java.util.Arrays;
public class BoxNumDemo {
static int[][] datas = new int[3+2][4+2];
static int[] visit = new int[10];
static int result = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0;i<datas.length;i++){
Arrays.fill(datas[i], -9);
}
dfs(1,2);
System.out.print(result);
}
public static void dfs(int dep,int pos){
if(dep==3&&pos==4){
System.out.println("找打了一種解決方案");
for(int i=1;i<=3;i++){
for(int j=1;j<=4;j++){
System.out.print(datas[i][j]+" ");
}
System.out.println();
}
result ++;
return;
}else{
if(pos<=4){
for(int i=0;i<10;i++){
if(visit[i]==0&&!hasOther(dep,pos,i)){
datas[dep][pos]=i;
visit[i]=1;
dfs(dep,pos+1);
datas[dep][pos]=-9;
visit[i]=0;
}
}
}else{
dfs(dep+1,1);
}
}
}
public static boolean hasOther(int dep,int pos,int num){
boolean result = false;
if(Math.abs(datas[dep+1][pos]-num)==1||
Math.abs(datas[dep][pos+1]-num)==1||
Math.abs(datas[dep+1][pos+1]-num)==1||
Math.abs(datas[dep-1][pos]-num)==1||
Math.abs(datas[dep][pos-1]-num)==1||
Math.abs(datas[dep-1][pos-1]-num)==1||
Math.abs(datas[dep+1][pos-1]-num)==1||
Math.abs(datas[dep-1][pos+1]-num)==1
){
result = true;
}
return result;
}
}
執行結果 :