알고리즘/백준

브론즈3 - 행렬 덧셈

요술공주밍키 2025. 5. 12. 16:10

https://www.acmicpc.net/problem/2738

 

 ✅문제 풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    public static void solution() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

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

        int[][] A = new int[N][M];
        int[][] B = new int[N][M];
        int[][] C = new int[N][M];

        for (int i=0; i<N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j=0; j<M; j++) {
                A[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        for (int i=0; i<N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j=0; j<M; j++) {
                B[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        for (int i=0; i<N; i++) {
            for (int j=0; j<M; j++) {
                C[i][j] = A[i][j] + B[i][j];
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int i=0; i<N; i++) {
            for (int j=0; j<M; j++) {
                sb.append(C[i][j]).append(' ');
            }
            sb.append('\n');
        }

        System.out.print(sb.toString());
        br.close();
    }

    public static void main(String[] args) {
        try {
            solution();
        } catch(IOException e) {
            System.out.println(e);
        }
    }
}

 

BufferedReader와 StringTokenizer를 이용해 입력값을 받기

 

행렬에 입력 값 저장해 둔 뒤 계산하기

 

계산된 결과 출력하기