矩陣乘法

題目描述

若是A是個x行y列的矩陣,B是個y行z列的矩陣,把A和B相乘,其結果將是另外一個x行z列的矩陣C。
這個矩陣的每一個元素是由下面的公式決定的:

原型:
voidmatrix_multiply(int *m1,int *m2,int *r, int x, int y, int z);
輸入參數:
    int *m1:x行y列的矩陣(array1[x][y])
    int *m2:y行z列的矩陣(array2[y][z])
    int x:矩陣m1的行數
    int y:矩陣m1的列數/矩陣m2的行數
    int z:矩陣m2的列數
輸出參數:
    int *r:矩陣m1, m2相乘的結果(array3[x][z])
返回值:
    void

輸入描述

輸入說明:
一、第一個矩陣的行數
二、第一個矩陣的列數和第二個矩陣的行數
三、第二個矩陣的列數
四、第一個矩陣的值
五、第二個矩陣的值

輸出描述

輸出兩個矩陣相乘的結果

輸入例子

2
2
2
3 8
8 0
9 0
18 9

輸出例子

171 72
72 0

算法實現

import java.util.Scanner;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            int x = scanner.nextInt();
            int y = scanner.nextInt();
            int z = scanner.nextInt();

            int[][] a = new int[x][y];
            int[][] b = new int[y][z];


            for(int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    a[i][j] = scanner.nextInt();
                }
            }

            for(int i = 0; i < y; i++) {
                for (int j = 0; j < z; j++) {
                    b[i][j] = scanner.nextInt();
                }
            }


            System.out.println(matrixMultiply(a, b));
        }

        scanner.close();
    }

    private static String matrixMultiply(int[][] a, int[][] b) {
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < b[0].length; j++) {
                int result = 0;
                for (int k = 0; k < a[0].length; k++) {
                    result += a[i][k] * b[k][j];
                }

                builder.append(result).append(' ');
            }
            builder.setCharAt(builder.length() - 1, '\n');
        }

        return builder.substring(0, builder.length() - 1);
    }
}
相關文章
相關標籤/搜索