알고리즘

백준 8911번 거북이 (JAVA)

박카스마시며코딩 2023. 12. 15. 20:47

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

 

8911번: 거북이

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고, 컨트롤 프로그램이 주어진다. 프로그램은 항상 문제의 설명에 나와있는 네가지 명령으로만 이루어져

www.acmicpc.net

 

저는 구현을 통해 문제를 풀었습니다.

해당 경로에서 제일 작은 y값 제일 큰 y값 제일 작은 x값, 제일 큰 x값을 찾고 이들을 통해 사각형의 너비를 찾아 문제를 풀었습니다.

 

package BOJ.simulation;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BOJ_8911_2 {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int testCnt = Integer.parseInt(br.readLine());
        for (int t = 0; t < testCnt; t++) {
            String command = br.readLine();
            int result = cal(command);
            System.out.println(result);
        }
    }

    private static final int[] DY = {-1, 0, 1, 0};
    private static final int[] DX = {0, 1, 0, -1};
    private static final char GO = 'F';
    private static final char BACK = 'B';
    private static final char LEFT = 'L';
    private static final char RIGHT = 'R';
    private static int cal(String command) {
        int maxY = 0;
        int minY = 0;
        int maxX = 0;
        int minX = 0;
        int dir = 0;
        int y = 0;
        int x = 0;
        for (int i = 0; i < command.length(); i++) {
            char ch = command.charAt(i);
            if (ch == GO) {
                y += DY[dir];
                x += DX[dir];
            }
            if (ch == BACK) {
                y -= DY[dir];
                x -= DX[dir];
            }
            if (ch == LEFT) {
                dir = (dir - 1 + 4) % 4;
            }
            if (ch == RIGHT) {
                dir = (dir + 1) % 4;
            }
            maxY = Math.max(maxY, y);
            minY = Math.min(minY, y);
            maxX = Math.max(maxX, x);
            minX = Math.min(minX, x);
        }
        return (maxY - minY) * (maxX - minX);
    }

}