矩阵乘法

矩阵乘法

http://www.nowcoder.com/questionTerminal/ebe941260f8c4210aa8c17e99cbc663b

暴力解

import java.util.*;
public class Main {
    public Main() {
    }
    public int[][] mul(int[][] mat1, int [][]mat2) {
        int x = mat1.length, y = mat2.length, z = mat2[0].length;
        int[][] res = new int[x][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < z; j++) {
                for (int k = 0; k < y; k++) {
                    res[i][j] += mat1[i][k] * mat2[k][j];
                }
            }
        }
        return res;
    }
    public static void main(String[] args) {
        Main solution = new Main();
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int x = in.nextInt(), y = in.nextInt(), z = in.nextInt();
            int[][] mat1 = new int[x][y];
            int[][] mat2 = new int[y][z];
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < y; j++) {
                    mat1[i][j] = in.nextInt();
                }
            }
            for (int i = 0; i < y; i++) {
                for (int j = 0; j < z; j++) {
                    mat2[i][j] = in.nextInt();
                }
            }
            int[][] res = solution.mul(mat1, mat2);
            for (int i = 0; i < x; i++) {
                for (int j = 0; j < z; j++) {
                    System.out.print(res[i][j] + " ");
                }
                System.out.println();
            }
        }
    } 
}
全部评论
其实把下面的mul方法改为static 修饰的话main()方法中就不需要new Main() ,同时也不需要定义它的构造方法了... 不过呢,还是要感谢楼主的分享哈!!!
1 回复 分享
发布于 2022-08-27 11:41 陕西
题主不设为静态方法,可能担心某些参数加载出问题。派仔在某一道题下的解答就是如此做的
点赞 回复 分享
发布于 2023-02-21 19:45 浙江

相关推荐

点赞 评论 收藏
分享
18 5 评论
分享
牛客网
牛客企业服务