确定矩阵是否是魔法

时间:2014-12-02 19:59:08

标签: java matrix multidimensional-array

我需要确定魔方是否是魔法。我需要比较每一行的总和和每一列的总和,然后将它们与对角线的总和进行比较,然后与另一个矩阵的总和进行比较。

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

如果方形是魔术,我需要它返回true(否则所有行,cols和diagonals都有相同的总和)

我如何设置此代码?

1 个答案:

答案 0 :(得分:1)

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));
   }
}