문제 풀이/백준

[백준]16967번. 배열 복원하기(JAVA)

27200 2024. 9. 27. 16:45

문제

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


풀이

import java.io.*;
import java.util.*;

public class Main {
    static int h, w, x, y;

    static int[][] arrB;
    static int[][] arrA;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        st = new StringTokenizer(br.readLine());
        h = Integer.parseInt(st.nextToken());
        w = Integer.parseInt(st.nextToken());
        x = Integer.parseInt(st.nextToken());
        y = Integer.parseInt(st.nextToken());
        arrA = new int[h][w];
        arrB = new int[h+x][w+y];

        for(int i = 0; i < h+x; i++){
            st = new StringTokenizer(br.readLine());
            for(int j = 0; j < w+y; j++){
                arrB[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        firstArrA(arrB);
        secondArrA();
        answer();
    }

    private static void firstArrA(int[][] arrB){
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                arrA[i][j] = arrB[i][j]; // B배열에서 A부분 만큼만 발췌
            }
        }
    }

    private static void secondArrA(){
        for(int i = x; i < h; i++){
            for(int j = y; j < w; j++){
                arrA[i][j] -= arrA[i-x][j-y]; // 옮기기 전의 칸에 대한 값을 제거해줌.
            }
        }
    }
    // 0,0 / 0,1 / 0,2 가 1,1 / 1,2 / 1,3 으로 바뀜

    private static void answer(){ // 정답 배열을 출력한다
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                System.out.print(arrA[i][j] + " "); // 한 칸 씩 공백을 두고 출력하게 됨
            }
            System.out.println();
        }
    }
}

어떤 칸을 옮겨서 값을 빼주면 되는지에 대한 정확한 이해만 있으면 어렵지 않은 문제이다. 이 전의 문제와 동일하게 정답 배열을 출력하는 메서드를 따로 둠으로써 여러 번 출력 혹은 디버깅을 해보며 문제에 대한 정확한 이해를 연습하는 것이 좋을 것 같다.

 

추가적으로 정답을 보았을 때 한칸씩 띄운 뒤 출력하는 것을 볼 수 있다. 이에 대한 정확한 체크도 중요할 것 같다.