题解 | #矩阵乘法#
矩阵乘法
https://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int y = sc.nextInt(); int z = sc.nextInt(); //xy * yz => xz int[][] xy = new int[x][y]; int[][] yz = new int[y][z]; int[][] xz = new int[x][z]; for(int i=0; i<x; i++){ for(int j=0; j<y; j++){ xy[i][j] = sc.nextInt(); } } for(int i=0; i<y; i++){ for(int j=0; j<z; j++){ yz[i][j] = sc.nextInt(); } } int[][] yzT = trans(yz, y, z); for(int i=0; i<x; i++){ for(int j=0; j<z; j++){ xz[i][j] = solution(xy[i], yzT[j]); System.out.print(xz[i][j] + " "); } System.out.println(""); } } //求乘和 private static int solution(int[] a, int[] b){ int res = 0; for(int i=0; i<a.length; i++){ res += (a[i] * b[i]); } return res; } //矩阵转置 private static int[][] trans(int[][] rc, int r, int c){ int[][] cr = new int[c][r]; for(int i=0; i<c; i++){ for(int j=0; j<r; j++){ cr[i][j] = rc[j][i]; } } return cr; } }