Blue Bridge Cup ALGO-86 Matrix Multiplication Java

Problem Description

问题描述
  输入两个矩阵,分别是m*s,s*n大小。输出两个矩阵相乘的结果。
输入格式
  第一行,空格隔开的三个正整数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

Problem-solving ideas

The matrix C should be m rows and n columns, where C(i,j) is equal to the inner product of the i-th row and row vector of the matrix A and the j-th column and column vector of the matrix B.
For example, in the example, C(1,1)=(1,0,-1)*(0,1,3) = 1 * 0 +0*1+(-1)*3=-3

Reference Code

package 矩阵乘法;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
	Scanner sr = new Scanner( System.in);
	int m = sr.nextInt();
	int s = sr.nextInt();
	int n = sr.nextInt();
	//生成矩阵
	int[][] map1 = new int[m][s];
	int[][] map2 = new int[s][n];
	//输入矩阵
	for (int i = 0; i < map1.length; i++) {
		for (int j = 0; j < map1[0].length; j++) {
			map1[i][j] = sr.nextInt();
		}
	}
	for (int i = 0; i < map2.length; i++) {
		for (int j = 0; j < map2[0].length; j++) {
			map2[i][j] = sr.nextInt();
		}
	}
	//生成结果矩阵
	int[][] result  = new int[m][n];
	for (int i = 0; i < result.length; i++) {
		for (int j = 0; j < result[0].length; j++) {
			//result[i][j] = 矩阵1第i行 * 矩阵2第j列
			for (int k = 0; k < s; k++) {
				result[i][j] += map1[i][k] * map2[k][j];
			}
		}
	}
	//输出
	for (int i = 0; i < result.length; i++) {
		for (int j = 0; j < result[0].length; j++) {
			System.out.print(result[i][j]+" ");
		}System.out.println();
	}
}
}

 

Guess you like

Origin blog.csdn.net/qq_40185047/article/details/114655568