文系プログラマーのプログラミング備忘録

Java、競プロ、数学などについて書いてます

Matrix Multiplication [ AIZU ONLINE JUDGE ITP1_7_D ]

judge.u-aizu.ac.jp



行列が2つ与えられるので、その積となる行列を求めよという問題です。


この問題のために行列同士の積の求め方を習得しましたが、相変わらず行列自体については何もわかっていません。それはともかくとして、いい機会だったので、次に行列の問題に出会ったときのために、行列同士の和・差・積を求めるメソッドもついでに作ってしまいました。例外処理も何もしていませんが、自分用ということでご容赦ください。

import java.util.*;

class Main {
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) {

		int n = sc.nextInt(); int m = sc.nextInt(); int l = sc.nextInt();
		int[][] row = new int[n][m];
		for (int i=0; i<n; i++) {
			for (int j=0; j<m; j++) {
				row[i][j] = sc.nextInt();
			}
		}
		int[][] column = new int[m][l];
		for (int i=0; i<m; i++) {
			for (int j=0; j<l; j++) {
				column[i][j] = sc.nextInt();
			}
		}

		long[][] ans = calcMatrix(row, column, "*");

		for (int i=0; i<n; i++) {
			StringBuilder sb = new StringBuilder();
			for (int j=0; j<l; j++) {
				sb.append((j==0?"":" ")+(ans[i][j]));
			}
			System.out.println(sb);
		}

	}

	static long[][] calcMatrix(int[][] row, int[][] column, String operator) {

		int rowH = row.length; int rowW = row[0].length;
		int columnH = column.length; int columnW = column[0].length;
		long[][] result = null;

		if (operator.equals("+")) {
			result = new long[rowH][rowW];
			for (int i=0; i<rowH; i++) {
				for (int j=0; j<rowW; j++) {
					result[i][j] = row[i][j] + column[i][j];
				}
			}
		}
		else if (operator.equals("-")) {
			result = new long[rowH][rowW];
			for (int i=0; i<rowH; i++) {
				for (int j=0; j<rowW; j++) {
					result[i][j] = row[i][j] - column[i][j];
				}
			}
		}
		else if (operator.equals("*")) {
			result = new long[rowH][columnW];
			for (int i=0; i<rowH; i++) {
				for (int j=0; j<columnW; j++) {
					long sum = 0;
					for (int k=0; k<rowW; k++) {
						sum += row[i][k] * column[k][j];
					}
					result[i][j] = sum;
				}
			}
		}
		
		return result;

	}

}