五星填数(dfs)

/*标题:五星填数   如【图1.png】的五星图案节点填上数字:1~12,除去7和11。 要求每条直线上数字和相等。   如图就是恰当的填法。   请你利用计算机搜索所
 * 有可能的填法有多少种。 注意:旋转或镜像后相同的算同一种填法。   请提交表示方案数目的整数,不要填写任何其它内容。*/
package test;

public class 五星填数 {
    static int count = 0;
    public static void main(String arg[])
    {
        int[] a = {1,2,3,4,5,6,8,9,10,12};
        dfs(0,9,a);
        System.out.println(count/10);
    }

    private static void dfs(int step, int length, int[] a) {
        // TODO Auto-generated method stub
        if(step == length)
        {
            if(check(a)){
                //System.out.println(count);
                count++;
            }
        }
        else
        {
            for(int i = step;i <= length;i++)
            {
                swap(i,step,a);
                dfs(step+1,length,a);
                swap(i,step,a);
            }
        }
    }

    private static boolean check(int[] a) {
        // TODO Auto-generated method stub
        int temp = a[0]+a[5]+a[6]+a[2];  
        if(temp != a[2]+a[8]+a[7]+a[4])  
            return false;  
        if(temp != a[4]+a[5]+a[9]+a[1])  
            return false;  
        if(temp != a[1]+a[6]+a[7]+a[3])  
            return false;  
        if(temp != a[3]+a[8]+a[9]+a[0])  
            return false;  
        return true;
    }

    private static void swap(int i, int step,int[] a) {
        // TODO Auto-generated method stub
        int temp = a[i];
        a[i] = a[step];
        a[step] = temp;
    }

}
原文地址:https://www.cnblogs.com/ljs-666/p/8779554.html