문제풀이/백준

[백준]9019: DSLR - JAVA

빈둥벤둥 2021. 3. 7. 19:53

문제

www.acmicpc.net/problem/9019

 

9019번: DSLR

네 개의 명령어 D, S, L, R 을 이용하는 간단한 계산기가 있다. 이 계산기에는 레지스터가 하나 있는데, 이 레지스터에는 0 이상 10,000 미만의 십진수를 저장할 수 있다. 각 명령어는 이 레지스터에

www.acmicpc.net

풀이

A를 B로 표현할 수 있는 최소한의 방법을 출력하는 것이므로 BFS를 사용하였다. 

 

모든 경우에서 4가지 명령어를 실행하고 각각의 실행한 경우에서 또 명령어를 실행하도록 반복해 주었다. 이러다가 B가 되었을때 그때까지의 명령어를 반환하도록 하였다.

 

현재까지 사용된 명령어를 저장하기 위해서 Node 클래스를 사용해 주었다.

 

코드

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.*;
 
public class Main {    
    
    static char[] command = {'D''S''L''R'};
    static boolean[] visited;
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int t = scan.nextInt();
        for(int i = 0; i < t; i++) {
            int start = scan.nextInt();
            int target = scan.nextInt();
            visited = new boolean[10000];
            System.out.println(bfs(start, target));
        }
    }
    
    public static String bfs(int start, int target) {
        Queue<Node> q = new LinkedList<>();
        q.offer(new Node(start, ""));
        visited[start] = true;
        
        while(!q.isEmpty()) {
            Node current = q.poll();
            if(current.register == target) return current.result;
            
            for(int i = 0; i < 4; i++) {
                int change = changeRegister(current.register, command[i]);
                if(visited[change] == false) {
                    visited[change] = true;
                    q.offer(new Node(change, current.result + command[i]));
                }
            }
        }
        return "";
    }
    
    public static int changeRegister(int register, char command) {
        if(command == 'D') {
            register *= 2;
            if(register > 9999) register %= 10000;
        } else if(command == 'S') {
            register -= 1;
            if(register == -1) register = 9999;
        } else if(command == 'L') {
            int temp1 = (register % 1000* 10;
            int temp2 = register / 1000;
            register = temp1 + temp2;
        } else {
            int temp1 = register / 10;
            int temp2 = (register % 10* 1000;
            register = temp1 + temp2;
        }
        return register;
    }
 
    public static class Node {
        int register;
        String result;
        
        public Node(int register, String result) {
            this.register = register;
            this.result = result;
        }
    }    
}
cs