题解 | #矩阵乘法#

矩阵乘法

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

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int x = Integer.valueOf(scan.nextLine().trim());
        int y = Integer.valueOf(scan.nextLine().trim());
        int z = Integer.valueOf(scan.nextLine().trim());
        int[][] m1 = new int[x][y];
        int[][] m2 = new int[y][z];
        for (int i = 0; i < x; i++) {
            String[] tmp = scan.nextLine().split(" ");
            for (int j = 0; j < y; j++) {
                m1[i][j] = Integer.valueOf(tmp[j]);
            }
        }
        for (int i = 0; i < y; i++) {
            String[] tmp = scan.nextLine().split(" ");
            for (int j = 0; j < z; j++) {
                m2[i][j] = Integer.valueOf(tmp[j]);
            }
        }
        int[][] ans = new int[x][z];
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < z; j++) {
                int tmp = 0;
                for (int k = 0; k < y; k++) {
                    tmp += m1[i][k] * m2[k][j];
                }
                ans[i][j] = tmp;
            }
        }
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < z; j++) {
                if (j == z - 1) {
                    System.out.println(ans[i][j]);
                    break;
                }
                System.out.print(ans[i][j] + " ");
            }
        }
    }
}
全部评论
该牛油正在参与牛客写题解薅羊毛的活动,牛币,周边,京东卡超多奖品放送,活动进入倒计时!快来捡漏啦https://www.nowcoder.com/discuss/888949?source_id=profile_create_nctrack&channel=-1
点赞 回复 分享
发布于 2022-04-20 17:00

相关推荐

11-24 19:04
已编辑
湖南工商大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务