-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDH_86052.java
More file actions
108 lines (80 loc) Β· 3.44 KB
/
DH_86052.java
File metadata and controls
108 lines (80 loc) Β· 3.44 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import java.util.*;
/*
* λΉμ κ²½λ‘ μ¬μ΄ν΄
*/
public class DH_86052 {
static class Node {
// Nodeκ° [r][c] μ§μ μΌ λ, [r][c]μμ dir λ°©ν₯μΌλ‘ κ° λ, νμ¬ κ±°λ¦¬
// λ³μλͺ
μ dirμ΄μ§λ§, λ°©ν₯μ΄ μλ 거리λ₯Ό μ μ₯
int[] dir;
public Node(int[] dir) {
this.dir = dir;
}
}
static int[] dr = {-1, 0, 1, 0}, dc = {0, 1, 0, -1}; // μ, μ°, ν, μ’
static int[] solution(String[] grid) {
int row = grid.length, column = grid[0].length();
ArrayList<Integer> answerList = new ArrayList<>();
// λΉμ κ²½λ‘λ€ μ μ₯
Node[][] nodeMap = initNodeMap(row, column);
// λͺ¨λ 격μ νμΈ
for(int r = 0; r < row; r++) {
for(int c = 0; c < column; c++) {
// ν 격μμ λν΄ μ, μ°, ν, μ’ λͺ¨λ νμΈ
for(int d = 0; d < 4; d++) {
// μ¬μ΄ν΄μ΄ λ°μνλμ§ νμΈ (μ¬μ΄ν΄ λ°μ β 0 λ³΄λ€ ν° μ«μ λ°ν)
int cycleLength = getCycleLength(grid, nodeMap, r, c, d);
if(cycleLength == 0) continue;
answerList.add(cycleLength);
}
}
}
Collections.sort(answerList);
int[] answer = new int[answerList.size()];
for(int i = 0; i < answerList.size(); i++) answer[i] = answerList.get(i);
return answer;
}
// μ¬μ΄ν΄μ΄ λ°μνλμ§ νμΈνλ ν¨μ
static int getCycleLength(String[] grid, Node[][] nodeMap, int sr, int sc, int sd) {
char startCh = grid[sr].charAt(sc);
if(startCh == 'L') sd = (sd + 4 - 1) % 4;
if(startCh == 'R') sd = (sd + 4 + 1) % 4;
// μ΄κΈ° μμ μ’νμ λ°©ν₯ μ μ₯
int initR = sr, initC = sc, initD = sd;
int dis = 0;
int r = grid.length, c = grid[0].length();
while(true) {
// disκ° 0μ΄ μλλ©΄μ νμ¬ μμ μ’νμ λ°©ν₯μ΄ μ΄κΈ° μ’νμ λ°©ν₯κ³Ό κ°λ€λ©΄ μ¬μ΄ν΄μ΄ λ°μν κ²
if(dis != 0 && sr == initR && sc == initC && sd == initD) return dis;
if(nodeMap[sr][sc].dir[sd] != 0) break; // λ§μ½μ dir[sd] != 0μ΄λΌλ©΄ μ΄λ―Έ μ¬μ΄ν΄μ΄ λ°μνλμ§ νμΈν κ²½λ‘
// νμ¬ μ’νμμ κ°μΌλλ λ°©ν₯μ κ±°λ¦¬λ‘ μ±μλ£κΈ°
nodeMap[sr][sc].dir[sd] = ++ dis;
// λ€μ μ’ν ꡬνκΈ°
int nr = (sr + r + dr[sd]) % r;
int nc = (sc + c + dc[sd]) % c;
int nd = sd;
// λ€μ μ’νμμμ λ°©ν₯ ꡬνκΈ°
if(grid[nr].charAt(nc) == 'L') nd = (nd + 4 - 1) % 4;
if(grid[nr].charAt(nc) == 'R') nd = (nd + 4 + 1) % 4;
// νμ¬ μ’ν μ
λ°μ΄νΈ
sr = nr;
sc = nc;
sd = nd;
}
return 0;
}
static Node[][] initNodeMap(int row, int column) {
Node[][] nodeMap = new Node[row][column];
for(int r = 0; r < row; r++) {
for(int c = 0; c < column; c++) {
int[] dir = new int[4];
nodeMap[r][c] = new Node(dir);
}
}
return nodeMap;
}
public static void main(String[] args) {
String[] grid = {"SL", "LR"};
System.out.println(Arrays.toString(solution(grid)));
}
}