Post

[백준] 2738번 - 행렬 덧셈 [Java][C++]

[백준] 2738번 - 행렬 덧셈 [Java][C++]

문제 링크


1. 문제 풀이

두 행렬의 덧셈을 구현하는 문제로 행렬의 덧셈은 같은 행, 열에 위치한 원소의 합으로 구할 수 있다.


2. 코드

1. 구현 [Java]

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
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));
        StringBuilder sb = new StringBuilder();
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int M = Integer.parseInt(st.nextToken());

        int[][] mat = new int[N][M];
        for (int k = 0; k < 2; k++) {
            for (int i = 0; i < N; i++) {
                st = new StringTokenizer(br.readLine());

                for (int j = 0; j < M; j++) {
                    mat[i][j] += Integer.parseInt(st.nextToken());
                }
            }
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                sb.append(mat[i][j]).append(" ");
            }
            sb.append("\n");
        }

        System.out.println(sb);
    }
}

2. 구현 [C++]

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
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n, m;
    cin >> n >> m;

    vector<vector<int>> mat(n, vector<int>(m));
    for (int k = 0; k < 2; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int x;
                cin >> x;

                mat[i][j] += x;
            }
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cout << mat[i][j] << ' ';
        }
        cout << '\n';
    }
}

3. 풀이 정보

1. 구현 [Java]

언어시간메모리코드 길이
Java 11152 ms15796 KB975 B

2. 구현 [C++]

언어시간메모리코드 길이
C++ 170 ms2152 KB575 B

This post is licensed under CC BY 4.0 by the author.