java implements fourth-order magic square of the 6th Blue Bridge Cup

Posted by nahla123 on Wed, 31 Jul 2019 02:32:00 +0200

Magic Square of Fourth Order

Fill in 4 x 4 squares with numbers from 1 to 16 so that rows and columns follow

When the sum of two diagonals is equal, it satisfies such characteristics.

For: fourth order magic square.

Fourth-order magic squares may have many solutions. If the upper left corner is fixed to 1

Please calculate the total number of options.
For example:
1 2 15 16
12 14 3 5
13 7 10 4
8 11 6 9

And:
1 12 13 8
2 14 7 11
15 3 10 6
16 5 4 9

It can be counted as two different schemes.

Please submit all the program numbers fixed at 1 in the upper left corner. No.

Fill in any superfluous content or explanatory text.

Answer: 416

import java.util.ArrayList;

public class Main {
    public static boolean[] used = new boolean[17];
    public static ArrayList<String> list = new ArrayList<String>();
    public static int count = 0;
    
    public boolean check(int[] A, int step) {
        if(step >= 4)
            if(A[0] + A[1] + A[2] + A[3] != 34)
                return false;
        if(step >= 8)
            if(A[4] + A[5] + A[6] + A[7] != 34)
                return false;
        if(step >= 12)
            if(A[8] + A[9] + A[10] + A[11] != 34)
                return false;
        if(step >= 13)
            if(A[0] + A[4] + A[8] + A[12] != 34 || A[3] + A[6] + A[9] + A[12] != 34)
                return false;
        if(step >= 14)
            if(A[1] + A[5] + A[9] + A[13] != 34)
                return false;
        if(step >= 15)
            if(A[2] + A[6] + A[10] + A[14] != 34)
                return false;
        if(step >= 16)
            if(A[3] + A[7] + A[11] + A[15] != 34 || A[0] + A[5] + A[10] + A[15] != 34)
                return false;
        return true;
    }
    
    public void dfs(int[] A, int step) {
        if(check(A, step) == false)
            return;
        if(step == 16) {
            StringBuffer s = new StringBuffer("");
            for(int i = 0;i < A.length;i++)
                s.append(A[i]);
            if(!list.contains(s.toString())) {
                list.add(s.toString());
                count++;
            }
            return;
        }
        for(int i = 2;i <= 16;i++) {
            if(used[i] == false) {
                used[i] = true;
                A[step] = i;
                dfs(A, step + 1);
                used[i] = false;
            }
        }
    }
    
    public static void main(String[] args) {
        Main test = new Main();
        int[] A = new int[16];
        A[0] = 1;
        used[1] = true;
        test.dfs(A, 1);
        System.out.println(count);
    }
}

Topics: Programming Java