算法设计 矩阵相乘 java

时间:2021-03-24 14:09:23
package day_30;

import java.util.Scanner;

/**
* 输入两个矩阵,分别是m*s,s*n大小。输出两个矩阵相乘的结果。
* Created by IamZY on 2018/1/21.
*/

public class Main {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int s = sc.nextInt();
int n = sc.nextInt();

int[][] j1 = new int[m][s];
int[][] j2 = new int[s][n];

for (int i = 0; i < m; i++) {
for (int j = 0; j < s; j++) {
j1[i][j] = sc.nextInt();
}
}

for (int i = 0; i < s; i++) {
for (int j = 0; j < n; j++) {
j2[i][j] = sc.nextInt();
}
}

showArrays(arrayMultiply(j1, j2, m, s, n),m,n);
}

public static int[][] arrayMultiply(int[][] a1, int[][] a2, int m, int s, int n) {
//2 3 2
int[][] newArr = new int[m][n];
int i, j, k;

for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < s; k++) {
newArr[i][j] += a1[i][k]*a2[k][j];
}
}
}

return newArr;
}

public static void showArrays(int[][] arr, int m, int s) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < s; j++) {
System.out.print(arr[i][j] + " ");

}
System.out.println();
}
}

}