题解 | #矩阵乘法#

矩阵乘法

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        int z = scanner.nextInt();
        int[][] xy = new int[x][y];
        int[][] yz = new int[y][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                xy[i][j] = scanner.nextInt();
            }
        }
        for (int i = 0; i < y; i++) {
            for (int j = 0; j < z; j++) {
                yz[i][j] = scanner.nextInt();
            }
        }
        int[][] result = metrixMutiply(xy, yz);
        for (int[] ints : result) {
            for (int j = 0; j < result[0].length; j++) {
                System.out.print(ints[j] + " ");
            }
            System.out.print("\n");
        }
    }

    public static int[][] metrixMutiply (int[][] mutiply1, int[][] mutiply2) {
        int x = mutiply1.length;
        int y1 = mutiply1[0].length;
        int y2 = mutiply2.length;
        int z = mutiply2[0].length;
        if (y1 != y2) System.out.println("ERROR");
        int[][] result = new int[x][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < z; j++) {
                result[i][j] = 0;
                for (int k = 0; k < y1; k++) {
                    result[i][j] += mutiply1[i][k] * mutiply2[k][j];
                }
            }
        }
        return result;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 13:15
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 12:10
点赞 评论 收藏
分享
昨天 12:17
已编辑
商丘师范学院 Java
后来123321:别着急,我学院本大二,投了1100份,两个面试,其中一个还是我去线下招聘会投的简历,有时候这东西也得看运气
无实习如何秋招上岸
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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