1. 程式人生 > >【華為機試069】矩陣乘法

【華為機試069】矩陣乘法

題目描述:

如果A是個x行y列的矩陣,B是個y行z列的矩陣,把A和B相乘,其結果將是另一個x行z列的矩陣C。

Java實現:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int x = sc.nextInt();
            int y = sc.nextInt();
            int z = sc.nextInt();
            int[][] A = new int[x][y];
            int[][] B = new int[y][z];
            int[][] C = new int[x][z];
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    A[i][j] = sc.nextInt();
                }
            }
            for (int i = 0; i < y; i++) {
                for (int j = 0; j < z; j++) {
                    B[i][j] = sc.nextInt();
                }
            }

            for (int i = 0; i < x; i++) {
                for (int j = 0; j < z; j++) {
                    C[i][j] = helper(A, B , i, j, y);
                    if (j != z-1)
                        System.out.print(C[i][j] + " ");
                    else 
                        System.out.print(C[i][j]);
                }
                System.out.println();
            }


        }
    }

    private static int helper(int[][] A, int[][] B, int i, int j, int y) {
        int sum = 0;
        for (int k = 0; k < y ; k++) {
            sum += A[i][k] * B[k][j];
        }
        return sum;
    }


}

知識點:

  • 需要注意x,y,z三者之間的關係