二维数组未按预期更新

时间:2013-11-29 09:29:20

标签: arrays 2d output

我在4x4阵列上运行以下代码:

private static final int DIMENSION = 4, MAXIMUM = 99;

public static int[][] floydAlgorithm(int[][] oldMatrix)
{
    int[][] newMatrix = new int[oldMatrix.length][oldMatrix[0].length];

    // nested for loops that update the new matrix with the minimum between the
    // old array entry and the sum of two elements along the same row and
    //column of the old array entry
    for (int x = 0; x < oldMatrix.length; x++)
    {
        for (int y = 0; y < oldMatrix[0].length; y++)
        {
            for (int i = 0; i < DIMENSION; i++)
                newMatrix[x][y] = Math.min(oldMatrix[x][y], 
                        oldMatrix[x][i] + oldMatrix[i][y]);
        }
    }

    return newMatrix;
}

public static void fillFloydMatrix(int[][] matrix) // fills 2d array with values
{
    int [] allInts = {0, 7, 5, MAXIMUM, MAXIMUM, 0, 7, 6,
            MAXIMUM, MAXIMUM, 0, MAXIMUM, 4, 1, 11, 0};

    for (int x = 0; x < matrix.length; x++)
        for (int y = 0; y < matrix[0].length; y++)
            matrix[x][y] = allInts[DIMENSION * x + y];
}

public static void displayMatrix(int[][] matrix)
{
    for (int x = 0; x < matrix.length; x++)
    {
        for (int y = 0; y < matrix[0].length; y++)
            System.out.print(matrix[x][y] + " ");

        System.out.println();
    }
}

public static void main(String[] args)
{
    int[][] floydMatrix = new int[DIMENSION][DIMENSION];

    fillFloydMatrix(floydMatrix);

    displayMatrix(floydMatrix);

    floydMatrix = floydAlgorithm(floydMatrix);

    System.out.println();

    displayMatrix(floydMatrix);
}

出于某种原因,此代码输出下面的两个数组,第一个按预期打印但第二个不打印:

0,7,5,99

99,0,7,6

99,99,0,99

4,1,11,0

*

0,7,5,99

10,0,7,6

99,99,0,99

4,1,11,0

最左边一列,第二行的99,正确更新为10([1] [3] + [3] [0],6 + 4)但最右上角99不更新为13([0] [1] + [1] [3],7 + 6)和底部的11不更新为8([1] [2] + [3] [1],7 + 1)。我试图找出原因,但最终,我没有找到问题所在的运气。因此,我寻求帮助找到原因?非常感谢你的帮助和提前的时间,当然,我会继续研究为什么会出现这种行为,但额外的眼睛不会受到伤害。

1 个答案:

答案 0 :(得分:1)

更改此

newMatrix[x][y] = Math.min(oldMatrix[x][y], 
                    oldMatrix[x][i] + oldMatrix[i][y]);

用这个:

newMatrix[x][y] = Math.min(newMatrix[x][y], 
                    oldMatrix[x][i] + oldMatrix[i][y]);

您还需要填写Integer.MAX_VALUE来初始化新矩阵。请参阅Arrays.fill