algorithm/문제 풀이

백준 2740번 (행렬 곱셈) 자바 Java11

ssoheeh 2021. 1. 26. 23:48

문제 : 행렬 곱셈

시간 제한 : 1 sec

메모리 제한 : 128 MB

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.io.*;
import java.util.*;
 
public class Main {
    public static void main(String[] args) throws IOException{
//        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                a[i][j] = sc.nextInt();
            }
        }        
        
        m = sc.nextInt();
        int k = sc.nextInt();
        int[][] b = new int[m][k];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < k; j++) {
                b[i][j] = sc.nextInt();
            }
        }
        int[][] c = new int[n][k];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                for (int s = 0; s < m; s++) {
                    c[i][j] += a[i][s]*b[s][j];
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < k; j++) {
                System.out.print(c[i][j]+" ");
            }
            System.out.println();
        }
//        bw.flush();
//        br.close();
//        bw.close();
    }    
}    
cs

 

어려운 문제는 아니지만 행렬 곱셈 반복문이 3번 돌아가고 범위를 잘 지정할 것!
헷갈리면  직접 해보기