题解 | #矩阵乘法#

矩阵乘法

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;
    }
}

全部评论

相关推荐

10-25 02:13
门头沟学院 C++
_凡_:8.27笔试10.22评估
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务