题解 | #矩阵乘法#

矩阵乘法

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            // int a = in.nextInt();
            // int b = in.nextInt();
            // System.out.println(a + b);
            // 第一个矩阵的行数
            int xRow = in.nextInt();
            // 第一个矩阵的列数也是第二个矩阵的行数
            int xCol = in.nextInt();
            // 第二个矩阵的列数 
            int yCol = in.nextInt();
            // 创建第一个矩阵
            int[][] xMatrix = new int[xRow][xCol];
            // 构造第一个矩阵的值
            for(int i=0;i<xRow;i++){//x行
                for(int j=0;j<xCol;j++){//x列
                    xMatrix[i][j] = in.nextInt();
                }
            }
            // 创建第二个矩阵
            int[][] yMatrix = new int[xCol][yCol];
            // 构造第二个矩阵的值
            for(int i=0;i<xCol;i++){//y行
                for(int j=0;j<yCol;j++){//y列
                    yMatrix[i][j]= in.nextInt();
                }
            }
            // 创建第三个矩阵,行是第一个矩阵的行,列是第二个矩阵的列
            int[][] zMatrix = new int[xRow][yCol];
            // 构造第三个矩阵的值
            for(int i=0;i<xRow;i++){//z行也是x行
                for(int j=0;j<yCol;j++){//z列也是y列
                    for(int k=0;k<xCol;k++){// x列也是y行

                        zMatrix[i][j]+=xMatrix[i][k]*yMatrix[k][j];

                    }
                }
            }
            // 遍历zMatrix矩阵,并输出
            for(int i=0;i<xRow;i++){
                for(int j=0;j<yCol;j++){
                    System.out.print(zMatrix[i][j] +" ");
                    // if(j != yCol-1){
                    //     // 两个数之间增加空格
                    //     System.out.print(" ");
                    // }
                }

                // 换行
                System.out.println();
            }
        }
    }
}

全部评论

相关推荐

面了100年面试不知...:被割穿了才想起来捞人了
投递哔哩哔哩等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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