0
Trying to do chain matrix multiplication but the code throws an out of bound exception at 2 places, please help me eliminate it.
The exception occurs at 2 places
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
    at Recursive.Recursive_Matrix(Recursive.java:27)
    at Recursive.main(Recursive.java:15).

通过重复调用自身,使用以下递归的问题如下:

 mij =  0, if   i = j else it is

        min   ( mik + mk+1 j + ri-1 * rk * rj )    if  i < j
             i ≤ k < j

我认为它与 MAX 值为 99999 相关。或者,这将是由于其他一些比较。

 class Recursive{


    public static int SIZE = 7;
    public static int MAX = 99999;

    static int M[][] = new int[SIZE][SIZE];
    static int i, k, q, j;
    static int P[] = new int []  { 25,10,15,5,30,10,15};


    public static void main(String[] args)
    {

        Recursive_Matrix( 1, SIZE);
        Print_M();

       return;
    }

    static int Recursive_Matrix(int i, int j) 
    {
        if( i == j )
            return 0;
        else
        {
            M[i][j] = MAX;
            for(k = i; k <= j-1; k++)
            {
                q =  Recursive_Matrix(i, k) + Recursive_Matrix( k+1, j) +  ( P[i-1] * P[k] * P[j] );
                if( q < M[i][j])
                    M[i][j] = q;
            }
        }
        return M[i][j]; 
    }

//这个函数只是简单的用来打印矩阵的元素 //对角线元素都是0,其他元素都是通过上面的递归函数计算出来的。
static void Print_M() { for(int x = 1; x<= SIZE; x++) { for(int y = 1; y <= SIZE; y++) { System.out.println(M[x][y]+ " "); } System.out.println("\n"); } } }

4

1 回答 1

0

看看你的第一个电话Recursive_Matrix( 1, SIZE);。现在j=7和以后...M[j]......P[j]...由于索引以0. 使用您的调试器并逐步执行代码!

于 2013-05-02T22:08:37.947 回答