题解 | #矩阵乘法#

矩阵乘法

https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    static int x = 0;
    static int y = 0;
    static int z = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            x = sc.nextInt();
            y = sc.nextInt();
            z = sc.nextInt();

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

            int[][] b = new int[y][z];
            for (int i = 0; i < y; i++) {
                for (int j = 0; j < z; j++) {
                    b[i][j] = sc.nextInt();
                }
            }
            solution(a, b);
        }
    }

    private static void solution(int[][] a, int[][] b) {
        int[][] res = new int[x][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < z; j++) {
                res[i][j] = getRes(a, b, i, j);
                if (j == z - 1) {
                    System.out.print(res[i][j] + "\n");
                } else {
                    System.out.print(res[i][j] + " ");
                }
            }
        }
    }

    private static int getRes(int[][] a, int[][] b, int i, int j) {
        int sum = 0;
        for (int k = 0; k < y; k++) {
            sum += a[i][k] * b[k][j];
        }
        return sum;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务