문제
N_M크기의 행렬 A와 M_K크기의 행렬 B가 주어졌을 때, 두 행렬을 곱하는 프로그램을 작성하시오.
입력
첫째 줄에 행렬 A의 크기 N 과 M이 주어진다. 둘째 줄부터 N개의 줄에 행렬 A의 원소 M개가 순서대로 주어진다. 그 다음 줄에는 행렬 B의 크기 M과 K가 주어진다. 이어서 M개의 줄에 행렬 B의 원소 K개가 차례대로 주어진다. N과 M, 그리고 K는 100보다 작거나 같고, 행렬의 원소는 절댓값이 100보다 작거나 같은 정수이다.
출력
첫째 줄부터 N개의 줄에 행렬 A와 B를 곱한 행렬을 출력한다. 행렬의 각 원소는 공백으로 구분한다.
해결 방법
- 2차원 배열로 행렬 만들어서 곱한다.
- A의 ij 번째 값들을 B의 ji 번째 값들과 곱한 후 모두 더해야 하기 때문에 3중 for문을 사용한다.
코드
// 행렬 곱셈, 2740
public class Week06_2740 {
static int[][] a;
static int[][] b;
static int an;
static int am;
static int bn;
static int bm;
static int[][] result;
public static void main(String[] args) throws IOException {
input();
multiple();
output();
}
private static void multiple() {
for (int i = 0; i < an; i++) {
for (int j = 0; j < bm; j++) {
for (int k = 0; k < bn; k++) {
result[i][j] += a[i][k] * b[k][j];
}
}
}
}
private static void input() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] anm = br.readLine().split(" ");
an = Integer.parseInt(anm[0]);
am = Integer.parseInt(anm[1]);
a = inputMatrix(an, am, br);
String[] bnm = br.readLine().split(" ");
bn = Integer.parseInt(bnm[0]);
bm = Integer.parseInt(bnm[1]);
b = inputMatrix(bn, bm, br);
result = new int[an][bm];
}
private static int[][] inputMatrix(int n, int m, BufferedReader br) throws IOException {
int[][] temp = new int[n][m];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
temp[i][j] = Integer.parseInt(st.nextToken());
}
}
return temp;
}
private static void output() throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
for (int[] s : result) {
for (int ss : s) {
bw.write(ss+" ");
}
bw.write("\n");
}
bw.flush();
bw.close();
}
}
'algorithm' 카테고리의 다른 글
| [BOJ] 1743. 음식물 피하기 (1) | 2022.12.09 |
|---|---|
| [BOJ] 2160. DFS와 BFS (0) | 2022.12.09 |
| [BOJ] 11725. 트리의 부모 찾기 (0) | 2022.11.18 |
| [BOJ] 9934. 완전 이진 트리 (0) | 2022.11.18 |
| [BOJ] 9372. 상근이의 여행 (0) | 2022.11.18 |