[Programmers] 행렬의 곱셈 - 연습문제

동민·2021년 3월 11일
// 행렬의 곱셈 - 연습문제
public class MultiOfMatrix {

	// 2차원 행렬의 곱셈은 i*j x j*k 형태이므로 3중 for문으로 해결한다.
	public int[][] solution(int[][] arr1, int[][] arr2) {
		int[][] answer = new int[arr1.length][arr2[0].length];

		for (int i = 0; i < arr1.length; i++) {
			for (int j = 0; j < arr1[0].length; j++) {
				int temp = arr1[i][j];
				for (int k = 0; k < arr2[0].length; k++) {
					answer[i][k] += temp * arr2[j][k];
				}
			}
		}

		return answer;
	}

	public static void main(String[] args) {

		MultiOfMatrix s = new MultiOfMatrix();

		int[][] arr1 = { { 1, 4 }, { 3, 2 }, { 4, 1 } };
		int[][] arr2 = { { 3, 3 }, { 3, 3 } };
		int[][] arr3 = { { 2, 3, 2 }, { 4, 2, 4 }, { 3, 1, 4 } };
		int[][] arr4 = { { 5, 4, 3 }, { 2, 4, 1 }, { 3, 1, 1 } };

		s.solution(arr1, arr2);
		s.solution(arr3, arr4);

	}

}
profile
BE Developer

0개의 댓글