Java实现 蓝桥杯 算法训练 矩阵乘法

算法训练 矩阵乘法
时间限制:1.0s 内存限制:512.0MB
提交此题
问题描述
  输入两个矩阵,分别是ms,sn大小。输出两个矩阵相乘的结果。
输入格式
  第一行,空格隔开的三个正整数m,s,n(均不超过200)。
  接下来m行,每行s个空格隔开的整数,表示矩阵A(i,j)。
  接下来s行,每行n个空格隔开的整数,表示矩阵B(i,j)。
输出格式
  m行,每行n个空格隔开的整数,输出相乘後的矩阵C(i,j)的值。
样例输入
2 3 2
1 0 -1
1 1 -3
0 3
1 2
3 1
样例输出
-3 2
-8 2

提示
矩阵C应该是m行n列,其中C(i,j)等于矩阵A第i行行向量与矩阵B第j列列向量的内积。

import java.util.Scanner;


public class 矩阵乘法 {
	  public static void main(String[] args) {
	        Scanner scanner = new Scanner(System.in);
	        int m = scanner.nextInt();
	        int s = scanner.nextInt();
	        int n = scanner.nextInt();
	        int[][] a = new int[200][200];
	        int[][] b = new int[200][200];
	        for (int i = 0; i < m; i++) {
	            for (int j = 0; j < s; j++) {
	                a[i][j] = scanner.nextInt();
	            }
	        }
	        for (int i = 0; i < s; i++) {
	            for (int j = 0; j < n; j++) {
	                b[i][j] = scanner.nextInt();
	            }
	        }
	        int[][] c = new int[200][200];
	        for (int i = 0; i < m; i++) {
	            for (int j = 0; j < n; j++) {
	                for (int j2 = 0; j2 < s; j2++) {
	                    c[i][j] += a[i][j2]*b[j2][j];
	                }
	            }
	        }
	        for (int i = 0; i < m; i++) {
	            for (int j = 0; j < n; j++) {
	                System.out.print(c[i][j]+" ");
	            }
	            System.out.println();
	        }
	    }

}

原文地址:https://www.cnblogs.com/a1439775520/p/13079376.html