본문 바로가기

알고리즘(백준 등) 공부

SWEA 14362. 무한로봇

로봇이 원점에서 명령어를 받고 무한히 수행할 때 현재 위치에서 무한히 멀어진다면 무한을, 같은 곳만 이동하게 된다면 원점과의 거리의 최댓값을 출력하는 문제이다.

 

명령어는 왼쪽 혹은 오른쪽으로 방향전환, 바라보는 방향으로 전진 이렇게 세 가지가 있다. 주어진 명령어 덩어리를 4번 반복하여 원점으로 돌아온다면 같은 곳만 이동하게 되므로 이동하면서 거리의 최댓값을 출력하고, 4번 반복 결과가 원점이 아니라면 무한히 멀어지므로 무한을 출력한다.

long max = 0;
for(int i=0; i<line.length()*4; i++) {
    int index = i%line.length();
    if(line.charAt(index) == 'S') {
        r += directions[direction][0];
        c += directions[direction][1];
        max = Math.max(max, r*r + c*c);
        continue;
    }
                
    if(line.charAt(index) == 'L') {
        direction--;
        if(direction == -1) {
            direction = 3;
        }
        continue;
    }
    direction++;
    direction %= 4;
}
if(r != 0 || c != 0) {
    sb.append("oo").append('\n');
} else {
    sb.append(max).append('\n');
}

 

 

결과 코드는 다음과 같다.

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

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();
        int[][] directions = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
        for (int tc = 1; tc <= T; tc++) {
            sb.append('#').append(tc).append(' ');
            int r = 0, c = 0, direction = 0;
            String line = br.readLine();
            long max = 0;
            for(int i=0; i<line.length()*4; i++) {
                int index = i%line.length();
                if(line.charAt(index) == 'S') {
                    r += directions[direction][0];
                    c += directions[direction][1];
                    max = Math.max(max, r*r + c*c);
                    continue;
                }
                
                if(line.charAt(index) == 'L') {
                    direction--;
                    if(direction == -1) {
                        direction = 3;
                    }
                    continue;
                }
                direction++;
                direction %= 4;
            }
            if(r != 0 || c != 0) {
                sb.append("oo").append('\n');
            } else {
                sb.append(max).append('\n');
            }
        }
        
        br.close();
        System.out.print(sb);
    }
}