1. 程式人生 > >藍橋杯 基礎練習 矩陣乘法(java)

藍橋杯 基礎練習 矩陣乘法(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();
	}
}

}