<링크>

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


<풀이>

HashMap의 Key는 x좌표, Value는 해당하는 x좌표에 나왔던 y좌표들의 Set이다.

배열을 이용해 이미 나왔던 좌표인지 체크할수도있지만

라이브러리한번 써보고 싶어서 이렇게 했다.


<소스코드>

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
import java.io.*;
import java.util.*;
 
public class Main {
    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        HashMap<Integer, HashSet<Integer>> hm = new HashMap<>();
        try {
            br.readLine();
            String s = br.readLine();
            int x = 0, y = 0, ans = 1;
            HashSet<Integer> hs = new HashSet<>();
            hs.add(y);
            hm.put(x, hs);
 
            int len = s.length();
            for (int i = 0; i < len; ++i) {
                char c = s.charAt(i);
                switch (c) {
                case 'N':
                    ++y;
                    break;
                case 'S':
                    --y;
                    break;
                case 'W':
                    --x;
                    break;
                case 'E':
                    ++x;
                    break;
                }
                if (!hm.containsKey(x)) {
                    HashSet<Integer> tmp = new HashSet<>();
                    tmp.add(y);
                    hm.put(x, tmp);
                    ++ans;
                } else {
                    HashSet<Integer> tmp = hm.get(x);
                    if (!tmp.contains(y)) {
                        tmp.add(y);
                        ++ans;
                    }
                }
 
            }
            System.out.println(ans);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
    }
}
cs


+ Recent posts