codeground 연습문제 5 - 미궁속의 방

 이 문제 역시 연습문제 4와 같이 단순한 계산 문제이다.

직관적으로 생각할 때 dfs로 이동을 하면서 채우는 것이 일반적이다.

하지만 시간도 오래걸릴 뿐더러 stack 공간을 많이 사용하기 때문에 비효율적이다.

따라서 좌표에 따른 해당 칸의 값을 계산하는 것이 훨씬 간단하고 복잡도도

줄일 수 있는 방법이다.



 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
import java.util.Scanner;

class Solution {
    static int  T, N, K, cur, dir, x, y, reo, ceo, rs, term;
    static String input;
    static char[] chars;
    static long Answer;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        T = sc.nextInt();
        for (int i = 0; i < T; i++) {
            Answer = 0;N = sc.nextInt();K = sc.nextInt();
            input = "";x = 1; y = 1;
            sc.nextLine();input = sc.nextLine();
            chars = input.toCharArray(); Answer += 1;
            for (int j = 0; j < chars.length; j++) {
                switch (chars[j]) {
                    case 'U':x--;break;
                    case 'D':x++;break;
                    case 'L':y--;break;
                    case 'R':y++;break;
                    default:break;
                }
                rs = (x % 2 == 0) ? x * (x + 1) / 2 : x * (x - 1) / 2 + 1;
                term = 2 * x - 1;
                if (x % 2 == 0 && y % 2 == 0) {
                    rs += 2 * y/2 * y/2;rs += term * (y / 2 - 1);
                }else if (x % 2 == 0 && y % 2 == 1) {
                    rs += 2 * (y - 1) / 2 * (y - 1) / 2; rs += term * (y - 1) / 2;
                }else if (x % 2 == 1 && y % 2 == 0) {
                    rs += 2 * (y / 2 - 1) * (y / 2 - 1) + 2 * (y / 2 - 1);
                    rs += term * (y / 2);
                }else {
                    rs += 2 * (y / 2) * (y / 2) + 2 * (y / 2);
                    rs += term * (y / 2);
                }
                if (x + y > N + 1) {
                    rs -= (x + y - N - 1) * (x + y - N - 1);
                }
                Answer += rs;
            }

            System.out.println("Case #"+(i+1));
            System.out.println(Answer);
        }
    }
}

이 블로그의 인기 게시물

웹툰 무료로 볼 수 있는 사이트

BackJoon 1011, Fly me to the alpha centauri, 규칙 찾기 문제

BaekJoon 6591, 이항 쇼다운 조합문제