[Summer/Winter Coding(~2018)] 방문 길이
[Summer/Winter Coding(~2018)] 방문 길이
🙋♂️ 들어가며
이번 문제는 조건을 꼼꼼하게 잘 봐야하는 문제였다.
캐릭터가 처음 걸어본 길이를 측정할 것
test case 1을 확인한 결과 아래와 같이 길이가 7로 형성되었다
5,5 -> 4,5 -> 4,4 -> 3,4 -> 3,6 -> 4,6 -> 4,5
값이 중복되었는데도 좌표를 인정하고 길이에 합산하니 동서남북 방향값을 추가하여 3차원 배열이 필요하다고 생각했다.
생각할 것음 다음과 같았다
- 양방향 처리
- nr, nc, nd = true
- cr, cc, reverse_d = true
- 범위가 밖이라면 다음으로 전환
- 양방향을 방문했다면 좌표만 갱신하고 다음으로 전환
- 양방향을 둘다 방문하지 않았다면 좌표 갱신, 길이를 갱신하고 다음으로 전환
✅ 코드
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Solution {
static int er = 10;
static int ec = 10;
static int sr = 0;
static int sc = 0;
public int solution(String dirs) {
int leng = 0;
int N = dirs.length();
char[] commands = new char[N];
for (int i = 0; i < N; i++) commands[i] = dirs.charAt(i);
// 1. 초기 시작
boolean[][][] visited = new boolean[10 + 1][10 + 1][4];
int cr = 5;
int cc = 5;
int i = 0;
while (i < N) {
char cur_button = commands[i];
int dr = 0;
int dc = 0;
int dd = 0;
if (cur_button == 'U') {
dr = -1;
dc = 0;
dd = 0;
}
else if (cur_button == 'D') {
dr = 1;
dc = 0;
dd = 1;
}
else if (cur_button == 'R') {
dr = 0;
dc = 1;
dd = 2;
}
else if (cur_button == 'L') {
dr = 0;
dc = -1;
dd = 3;
}
// 다음 좌표
int nr = cr + dr;
int nc = cc + dc;
int nd = dd;
// 2. 범위 밖 -> 다음으로 전환 후, skip
if (nr < sr || nr > er || nc < sc || nc > ec) {
i++;
continue;
}
// 3. 양방향 값 확인
int reverse_d = 0;
if (nd == 0) reverse_d = 1;
else if (nd == 1) reverse_d = 0;
else if (nd == 2) reverse_d = 3;
else if (nd == 3) reverse_d = 2;
// 4. 방문했다면 좌표를 갱신하고, 다음으로 전환하고 skip
if (visited[nr][nc][nd] || visited[cr][cc][reverse_d]) {
cr = nr;
cc = nc;
i++;
continue;
}
// 5. 양방향 방문 후에, 좌표 갱신
visited[nr][nc][nd] = true;
visited[cr][cc][reverse_d] = true;
leng++;
cr = nr;
cc = nc;
i++;
}
return leng;
}
}
This post is licensed under CC BY 4.0 by the author.

