-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain.java
More file actions
79 lines (63 loc) · 2.36 KB
/
Main.java
File metadata and controls
79 lines (63 loc) · 2.36 KB
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
package _2020_카카오_인턴십.P1;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.solution(new int[]{1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5}, "right"));
System.out.println(sol.solution(new int[]{7, 0, 8, 2, 8, 3, 1, 5, 7, 6, 2}, "left"));
System.out.println(sol.solution(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "right"));
System.out.println(sol.solution(new int[]{2, 5, 8, 0}, "right"));
}
}
class Solution {
static int[] dx = {-3, 3, -1, 1};
public String solution(int[] numbers, String hand) {
StringBuilder answer = new StringBuilder();
int left = 10, right = 12;
for (int n : numbers) {
boolean goLeft;
if (n == 1 || n == 4 || n == 7) goLeft = true;
else if (n == 3 || n == 6 || n == 9) goLeft = false;
else {
int left_count = move((left == 0) ? 11 : left, (n == 0) ? 11 : n);
int right_count = move((right == 0) ? 11 : right, (n == 0) ? 11 : n);
if (left_count < right_count) goLeft = true;
else if (left_count > right_count) goLeft = false;
else goLeft = hand.equals("left");
}
if (goLeft) {
left = n;
answer.append('L');
} else {
right = n;
answer.append('R');
}
}
return answer.toString();
}
private static int move(int start, int target) {
Queue<Integer> q = new LinkedList<>();
boolean[] visited = new boolean[13];
q.offer(start);
int count = 0;
while (!q.isEmpty()) {
int curSize = q.size();
while (curSize-- > 0) {
int cur = q.poll();
visited[cur] = true;
if (cur == target) return count;
for (int i = 0; i < 4; i++) {
if (cur % 3 == 0 && i == 3) continue;
if ((cur - 1) % 3 == 0 && i == 2) continue;
int to = cur + dx[i];
if (0 < to && to < 13 && !visited[to]) {
q.offer(to);
}
}
}
count ++;
}
return count;
}
}