코딩테스트/SWEA

[SWEA | Java] 파리퇴치3

박 성 하 2023. 12. 26. 19:00
728x90

문제

https://swexpertacademy.com/main/code/userProblem/userProblemDetail.do?contestProbId=AXuARWAqDkQDFARa&categoryId=AXuARWAqDkQDFARa&categoryType=CODE

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

티어

소요 시간

13분 31초

분류

브루트포스

코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;

public class Solution {

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

    static int[] plusDx = {-1, 1, 0, 0};
    static int[] plusDy = {0, 0, 1, -1};
    static int[] xDx = {-1, -1, 1, 1};
    static int[] xDy = {-1, 1, -1, 1};

    static int res;

    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 t = Integer.parseInt(br.readLine());
        for (int test = 1; test <= t; test++) {
            int[] line = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            n = line[0]; m = line[1];
            map = new int[n][n];
            for (int i = 0; i < n; i++) {
                map[i] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            }
            res = 0;

            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    res = Math.max(res, catchFly(i, j));
                }
            }

            bw.write("#" + test + " " + res + "\n");
            bw.flush();
        }
    }

    private static int catchFly(int y, int x) {
        int catchPlus = catching(y, x, true);
        int catchX = catching(y, x, false);

        return Math.max(catchPlus, catchX);
    }

    private static int catching(int y, int x, boolean isPlus) {
        int ans = map[y][x];
        int[] dx = plusDx, dy = plusDy;
        if (!isPlus) {
            dx = xDx;
            dy = xDy;
        }

        for (int i = 0; i < 4; i++) {
            int nextY, nextX;
            for (int j = 1; j < m; j++) {
                nextY = y + dy[i] * j;
                nextX = x + dx[i] * j;
                if (nextX >= 0 && nextX < n && nextY >= 0 && nextY < n) ans += map[nextY][nextX];
            }
        }

        return ans;
    }
}

코드 설명

plusDx, plusDy를 + 방향으로 스프레이를 분사했을 때 사용하는 델타,

xDx, xDy를 x 방향으로 스프레이를 분사했을 때 사용하는 델타로 이용했다.

 

함수를 두 개 둬서 따로 구할 수 있지만 코드의 중복을 피하기 위해서 boolean 값으로 isPlus인지 여부를 두었고 하나의 함수로 계산했다.

시간 손해는 조금 있겠지만 시간 손해에 비해 훨씬 코드가 깔끔해질 것이라고 생각해서 이런 풀이를 이용했다.

728x90