코딩테스트/Goorm

[구름톤 챌린지] 4-3. 중첩 점

박 성 하 2023. 9. 6. 16:50
728x90

코드

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

public class Main {

    static int n, m;
    static Line[][] map;

    static class Line {
        int row;
        int column;

        public Line(int row, int column) {
            this.row = row;
            this.column = column;
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int[] line = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        n = line[0]; m = line[1];
        map = new Line[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) map[i][j] = new Line(0, 0);
        }
        for (int i = 0; i < m; i++) {
            String[] s = br.readLine().split(" ");
            int y = Integer.parseInt(s[0]) - 1, x = Integer.parseInt(s[1]) - 1;
            drawLine(y, x, s[2]);
        }

        long cnt = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                cnt += (long) map[i][j].row * map[i][j].column;
            }
        }

        bw.write(Long.toString(cnt));
        bw.flush();
    }

    private static void drawLine(int y, int x, String dir) {
        switch (dir)
        {
            case "L" :
                for (int i = 0; i <= x; i++) map[y][i].row++;
                break;
            case "R":
                for (int i = x; i < n; i++) map[y][i].row++;
                break;
            case "U":
                for (int i = 0; i <= y; i++) map[i][x].column++;
                break;
            case "D":
                for (int i = y; i < n; i++) map[i][x].column++;
                break;
        }
    }
}

코드 설명

교차점은 '가로 선과 세로 선이 둘 다 존재할 경우' 생긴다.

따라서 Line이라는 클래스를 원소로 하는 2차원 배열을 선언하고 각 칸에 대한 가로 선과 세로 선의 개수를 따로 저장해두었다.

 

가로 선이 3개이고 세로 선이 2개 일 때 교차점은 3 * 2 = 6이다.

따라서 교차점의 개수는 '가로 선 * 세로 선'이다.

 

전에 풀었던 문제에서 했던 실수를 또 했는데 가로 선과 세로 선을 곱할 때 int형을 넘어갈 수 있다는 것이다.

마찬가지로 계산 식을 저장하는 변수만 long으로 설정했는데, 계산 식도 (long)으로 형변환하거나 가로 선과 세로 선의 개수를 long으로 저장하는 방법이 있다.

728x90