蓝桥杯 基础练习 矩阵乘法(java)

话不多说,直接上代码。
import java.util.Scanner;

public class Main4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][n];
int[][] t = new int[n][n];//记录中间数据的数组
int[][] r = new int[n][n];//记录最终结果的数组
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
t[i][j] = a[i][j];
}
}
//如果幂次为零,输出单位阵
if(m0){
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
if(i
j){
r[i][j] = 1;
}
}
}
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
System.out.print(r[i][j]+" ");
}
System.out.println();
}
return;
}
int k = 1;//记录当前计算的幂次
while (k < m) {
//每次循环将记录最终数据的数组清0,避免出现多次相加重复的数据
for(int i = 0;i<n;i++){
for(int j = 0;j<n;j++){
r[i][j] = 0;
}
}
int rows1 = 0, columns1 = 0, rows2 = 0, columns2 = 0;
int p = 0;//记录当前运算的前一项的行数;
int l;
int o = 0;//记录第几个数
while (p < n) {
l = 0;//记录当前运算的后一项矩阵的列数
while (l < n) {
o = 0;
rows1 = p;
columns1 = 0;
columns2 = 0;
rows2 = l;
while (o < n) {
r[p][l] += t[rows1][columns1]
* a[columns2][rows2];
columns1++;
columns2++;
o++;
}
l++;
}
p++;
}
//每循环一次都将最终数据赋给中间数据
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
t[i][j] = r[i][j];
}
}

		k++;
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < n; j++) {
			System.out.print(r[i][j] + " ");
		}
		System.out.println();
	}
}

}

猜你喜欢

转载自blog.csdn.net/SixA1024/article/details/84328851