8911번: 거북이

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

www.acmicpc.net

 

풀이 방법

거북이 로봇에게 내릴 수 있는 명령은 4가지

  1. F: 한 눈금 앞으로
  2. B: 한 눈금 뒤로
  3. L: 왼쪽으로 90도 회전
  4. R: 오른쪽으로 90도 회전 

거북이가 지나간 영역을 모두 포함하는 가장 작은 직사각형 넓이를 구하는 문제였습니다.

 

거북이 좌표를 nowX, nowY 변수에 담아두고 움직이면서 최소 X,Y 값 최대 X,Y값을 구해 이동이 다 끝난 뒤 넓이를 계산해주었습니다.

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class Main_BJ_8911_거북이 {
    
    static int [] dx = {-1,0,1,0};
    static int [] dy = {0,1,0,-1};
 
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        
        int T = Integer.parseInt(br.readLine());
        
        for(int i=0;i<T;i++) {
            int minX=0, minY=0, maxX=0, maxY=0, dir=0, nowX=0, nowY=0//초기값 북쪽
            
            String command = br.readLine();
            
            for(int j=0;j<command.length();j++) {
                char c = command.charAt(j);
                
                if(c=='F') { //한 눈금 앞으로
                    nowX = nowX+dx[dir];
                    nowY = nowY+dy[dir];
                }else if(c=='B') { //한 눈금 뒤로
                    nowX = nowX-dx[dir];
                    nowY = nowY-dy[dir];
                }else if(c=='L') { // 왼쪽으로 90도
                    if(dir==0) dir=3;
                    else dir--;
                }else if(c=='R') { // 오른쪽으로 90도
                    if(dir==3) dir=0;
                    else dir++;
                }
                
                minX = Math.min(minX, nowX);
                minY = Math.min(minY, nowY);
                maxX = Math.max(maxX, nowX);
                maxY = Math.max(maxY, nowY);
            }
            sb.append((Math.abs(minX)+Math.abs(maxX))*(Math.abs(minY)+Math.abs(maxY))+"\n");
        }
        System.out.println(sb.toString());
    }
 
}
cs

 

 

+ Recent posts