Skip to content

Commit c154e8a

Browse files
authored
Merge pull request #1042 from AlgorithmWithGod/Ukj0ng
[20251004] BOJ / G1 / 전구를 켜라 / 한종욱
2 parents 74747c4 + 7f5b9ac commit c154e8a

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+
```
2+
import java.io.*;
3+
import java.util.ArrayDeque;
4+
import java.util.Arrays;
5+
import java.util.Deque;
6+
import java.util.StringTokenizer;
7+
8+
public class Main {
9+
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
11+
private static final int[] dx = {1, 1, -1, -1};
12+
private static final int[] dy = {1, -1, 1, -1};
13+
private static final char[] need = {'\\', '/', '/', '\\'};
14+
private static int[][] dist;
15+
private static char[][] map;
16+
private static int N, M;
17+
18+
public static void main(String[] args) throws IOException {
19+
init();
20+
21+
int answer = BFS();
22+
23+
if (answer == -1) {
24+
bw.write("NO SOLUTION");
25+
} else {
26+
bw.write(answer + "");
27+
}
28+
bw.flush();
29+
bw.close();
30+
br.close();
31+
}
32+
33+
private static void init() throws IOException {
34+
StringTokenizer st = new StringTokenizer(br.readLine());
35+
N = Integer.parseInt(st.nextToken());
36+
M = Integer.parseInt(st.nextToken());
37+
38+
map = new char[N][M];
39+
dist = new int[N+1][M+1];
40+
41+
for (int i = 0; i < N; i++) {
42+
map[i] = br.readLine().toCharArray();
43+
}
44+
45+
for (int i = 0; i <= N; i++) {
46+
Arrays.fill(dist[i], Integer.MAX_VALUE);
47+
}
48+
}
49+
50+
private static int BFS() {
51+
Deque<int[]> dq = new ArrayDeque<>();
52+
dist[0][0] = 0;
53+
dq.add(new int[]{0, 0, 0});
54+
55+
while (!dq.isEmpty()) {
56+
int[] current = dq.poll();
57+
58+
if (dist[current[0]][current[1]] < current[2]) continue;
59+
60+
for (int i = 0; i < 4; i++) {
61+
int nx = current[0] + dx[i];
62+
int ny = current[1] + dy[i];
63+
64+
if (OOBPoint(nx, ny)) continue;
65+
66+
int gx = Math.min(current[0], nx);
67+
int gy = Math.min(current[1], ny);
68+
69+
if (OOBRange(gx, gy)) continue;
70+
71+
int cost = (map[gx][gy] == need[i]) ? 0 : 1;
72+
int newDist = dist[current[0]][current[1]] + cost;
73+
74+
if (newDist < dist[nx][ny]) {
75+
dist[nx][ny] = newDist;
76+
77+
if (cost == 0) {
78+
dq.addFirst(new int[]{nx, ny, newDist});
79+
} else {
80+
dq.addLast(new int[]{nx, ny, newDist});
81+
}
82+
}
83+
}
84+
}
85+
86+
return dist[N][M] == Integer.MAX_VALUE ? -1 : dist[N][M];
87+
}
88+
89+
private static boolean OOBPoint(int nx, int ny) {
90+
return nx < 0 || nx > N || ny < 0 || ny > M;
91+
}
92+
93+
private static boolean OOBRange(int gx, int gy) {
94+
return gx < 0 || gx >= N || gy < 0 || gy >= M;
95+
}
96+
}
97+
```

0 commit comments

Comments
 (0)