0

这是计算给定矩阵是否为幻方的子代码。我只是对重复的 test[element -1] 感到困惑并且有两个不同的返回。

public static boolean testNormal(int[][] matrix, int dim){

    int magicConstant = dim * (dim * dim +1) / 2;

    // checks if all the numbers are present
    // the default value is false
    boolean[] test = new boolean[dim*dim];
    int max = dim*dim;
    int element;
    for (int row = 0; row < dim; row++){
        for (int col = 0; col < dim; col++){
            element = matrix[row][col];
            if ((element > max)|| (element <= 0))
                return false;
            if (test[element -1])
                return false;
            test[element -1] = true;
        }
    }
4

1 回答 1

1

代码的格式不符合我的口味:

for (int col = 0; col < dim; col++){
    element = matrix[row][col];
    if ((element > max)|| (element <= 0)) {
        return false;
    }
    if (test[element -1]) {
        return false;
    }
    test[element -1] = true;
}

像这样写应该会更清楚一点。

因此,为了解释 if (test[element -1])从测试数组中获取位置 'element - 1' 的布尔值,如果它的计算结果为 true,我们输入 if 语句并返回 false。下一行没有执行,因为我们返回。

如果它评估为假,我们不输入 if 语句,并且 test[element - 1] 的值设置为真。

所以这不是重复,实例共享的唯一内容是它们访问数组中的相同位置。第一个实例从测试数组中获取并评估某些内容,第二个实例在测试数组中设置某些内容。

于 2020-04-17T11:37:05.727 回答