我需要确定魔术方块是否为魔术。我需要将每一行的总和与每一列的总和进行比较,然后将其与对角线的总和再与其他矩阵的总和进行比较。

我已经计算出每一行和每一列的总和,包括两个对角线。

如果正方形是魔术的,我需要它返回true(否则,所有行,列和对角线的总和都为false)

我将如何设置此代码?

最佳答案

public class MatrixService {

public static boolean isMagicSquare(int[][] arr) {
    final int size = arr.length;
    final int totalSize = size * size;
    final int magicNumber = (size * size * (size * size + 1) / 2) / size;
    int sumOfRow = 0, sumOfColoumns = 0, sumOfPrimaryDiagonal = 0, sumOfSecondaryDiagonal = 0;
    boolean[] flag= new boolean[size * size];

    for (int row = 0; row < size; row++) {
        sumOfRow = 0;
        sumOfColoumns = 0;
        for (int col = 0; col < size; col++) {
            if (arr[row][col] < 1 || arr[row][col] > totalSize) {
                return false;
            }
            if (flag[arr[row][col] - 1] == true) {
                return false;
            }
            flag[arr[row][col] - 1] = true;
            sumOfRow += arr[row][col];
            sumOfColoumns += arr[col][row];
        }
        sumOfPrimaryDiagonal += arr[row][row];
        sumOfSecondaryDiagonal += arr[row][n-row-1];

        if (sumOfRow != magicNumber || sumOfColoumns != magicNumber) {
            return false;
        }

        if (sumOfPrimaryDiagonal != magicNumber || sumOfSecondaryDiagonal != magicNumber) {
            return false;
        }

        return true;
    }

    public static void main(String []args){
        int[][] a ={{4,9,2},
                {3,5,7},
                {8,1,6}};
        System.out.println(isMagicSquare(a));
   }
}

关于java - 确定矩阵是否是魔术,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27257867/

10-09 22:52