二维数组

二维数组,每个元素的长度为t个字节,设为A的第一个元素,即二维数组的行下标从p到m,列下标从q到n,按“行优先顺序”存储时则元素的地址计算为:

按“列优先顺序”存储时,地址计算为:

存放该数组至少需要的单元数为(m-p+1) * (n-q+1) * t 个字节

二维数组又称为矩阵,行列数相等的矩阵称为方阵。对称矩阵,对角矩阵:n阶方阵的所有非零元素都集中在主对角线上.

二维数组基本运算算法:

(1)转置矩阵:

// 其中A, B是m*n矩阵
void tramat(matrix A, matrix B) { //T(n) = O(m * n)
    int i, j;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            B[j][i] = A[i][j];
}

(2)矩阵相加:

// 其中A,B,C是m*n矩阵
void addmat(matrix C, matrix A, matrix B) {
    int i, j;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            C[i][j] = A[i][j] + B[i][j];
}

(3)矩阵相乘:

// 其中A是m*r矩阵,B是r*n矩阵,C为m*n矩阵
void mutmat(matrix C, matrix A, matrix B) {
    int i, j, k;
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++) {
            C[i][j] = 0;
            for (k = 0; k < r; k++)
                C[i][j] += A[i][k] * B[k][j];
        }
}

参见

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.