Skip to content

Commit db60cc4

Browse files
authored
add : Programmers 80652 빛의경로사이클 풀이 추가 (#165)
1. 빛의경로사이클 문제 풀이 추가 end
1 parent 9787234 commit db60cc4

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package 아더;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
public class Pro_86052_빛의경로사이클 {
8+
9+
public static void main(String[] args) {
10+
Pro_86052_빛의경로사이클 pro = new Pro_86052_빛의경로사이클();
11+
String[] grid1 = {"SL","LR"};
12+
String[] grid2 = {"S"};
13+
String[] grid3 = {"R","R"};
14+
15+
System.out.println(Arrays.toString(pro.solution(grid1)));
16+
System.out.println(Arrays.toString(pro.solution(grid2)));
17+
System.out.println(Arrays.toString(pro.solution(grid3)));
18+
}
19+
20+
public int[] solution(String[] grid) {
21+
List<Integer> answer = new ArrayList<>();
22+
int[][] dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // 서 북 동 남
23+
24+
int row = grid.length;
25+
int col = grid[0].length();
26+
char[][] adj = new char[row][col];
27+
boolean [][][] visited = new boolean[row][col][dir.length];
28+
29+
// 입력 받기
30+
for (int i = 0; i < row; i++) {
31+
String[] split = grid[i].split("");
32+
for (int j = 0; j < col; j++) {
33+
adj[i][j] = split[j].charAt(0);
34+
}
35+
}
36+
37+
// 로직
38+
for (int i = 0; i < row; i++) {
39+
for (int j = 0; j < col; j++) {
40+
for (int k = 0; k < dir.length; k++) {
41+
if (visited[i][j][k]) continue;
42+
int cycleCount = 0;
43+
int tempRow = i;
44+
int tempCol = j;
45+
int tempDir = k;
46+
47+
// 4방향에서 각 점에 접근한다
48+
while (true) {
49+
// 각 점의 값에 따라 이동 및 방향 변경
50+
if (adj[tempRow][tempCol] == 'S') {
51+
// 방향 변경할 필요 없음
52+
tempRow = (tempRow + dir[tempDir][0] % 4) % row;
53+
tempCol = (tempCol + dir[tempDir][1] % 4) % col;
54+
} else if (adj[tempRow][tempCol] == 'L') {
55+
tempDir = (tempDir - 1 + 4) % 4;
56+
tempRow = (tempRow + dir[(tempDir) % 4][0]) % row;
57+
tempCol = (tempCol + dir[(tempDir) % 4][1]) % col;
58+
} else if (adj[tempRow][tempCol] == 'R') {
59+
tempDir = (tempDir + 1 + 4) % 4;
60+
tempRow = (tempRow + dir[(tempDir) % 4][0]) % row;
61+
tempCol = (tempCol + dir[(tempDir) % 4][1]) % col;
62+
}
63+
64+
// temp가 범위를 벗어나면 보정
65+
if (tempRow < 0) {
66+
tempRow = row - 1;
67+
}
68+
if (tempCol < 0) {
69+
tempCol = col - 1;
70+
}
71+
if (tempRow >= row) {
72+
tempRow = 0;
73+
}
74+
if (tempCol >= col) {
75+
tempCol = 0;
76+
}
77+
78+
// 방문했던 곳이면 사이클임
79+
if (visited[tempRow][tempCol][tempDir]) {
80+
break;
81+
}
82+
83+
// 방문 처리 및 사이클 수 증가
84+
visited[tempRow][tempCol][tempDir] = true;
85+
cycleCount++;
86+
}
87+
answer.add(cycleCount);
88+
}
89+
}
90+
}
91+
92+
return answer.stream()
93+
.mapToInt(num -> num)
94+
.sorted()
95+
.toArray();
96+
}
97+
}

0 commit comments

Comments
 (0)