Skip to content

Commit 2b047b7

Browse files
authored
Merge pull request #496 from AlgorithmWithGod/Seol-JY
[20250718] BOJ / G4 / 두 동전 / 설진영
2 parents 3a7ecf2 + fba6c98 commit 2b047b7

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed

Seol-JY/202507/18 G4 두 동전.md

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static int N, M;
7+
static char[][] board;
8+
static int[] dx = {-1, 1, 0, 0};
9+
static int[] dy = {0, 0, -1, 1};
10+
11+
static class State {
12+
int x1, y1, x2, y2, count;
13+
14+
State(int x1, int y1, int x2, int y2, int count) {
15+
this.x1 = x1;
16+
this.y1 = y1;
17+
this.x2 = x2;
18+
this.y2 = y2;
19+
this.count = count;
20+
}
21+
}
22+
23+
public static void main(String[] args) throws IOException {
24+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
25+
StringTokenizer st = new StringTokenizer(br.readLine());
26+
27+
N = Integer.parseInt(st.nextToken());
28+
M = Integer.parseInt(st.nextToken());
29+
30+
board = new char[N][M];
31+
List<int[]> coins = new ArrayList<>();
32+
33+
for (int i = 0; i < N; i++) {
34+
String line = br.readLine();
35+
for (int j = 0; j < M; j++) {
36+
board[i][j] = line.charAt(j);
37+
if (board[i][j] == 'o') {
38+
coins.add(new int[]{i, j});
39+
board[i][j] = '.';
40+
}
41+
}
42+
}
43+
44+
int result = bfs(coins.get(0)[0], coins.get(0)[1],
45+
coins.get(1)[0], coins.get(1)[1]);
46+
47+
System.out.println(result);
48+
}
49+
50+
static int bfs(int x1, int y1, int x2, int y2) {
51+
Queue<State> queue = new LinkedList<>();
52+
Set<String> visited = new HashSet<>();
53+
54+
queue.offer(new State(x1, y1, x2, y2, 0));
55+
visited.add(x1 + "," + y1 + "," + x2 + "," + y2);
56+
57+
while (!queue.isEmpty()) {
58+
State current = queue.poll();
59+
60+
if (current.count >= 10) {
61+
continue;
62+
}
63+
64+
for (int dir = 0; dir < 4; dir++) {
65+
int nx1 = current.x1 + dx[dir];
66+
int ny1 = current.y1 + dy[dir];
67+
int nx2 = current.x2 + dx[dir];
68+
int ny2 = current.y2 + dy[dir];
69+
70+
boolean out1 = isOutOfBounds(nx1, ny1);
71+
boolean out2 = isOutOfBounds(nx2, ny2);
72+
73+
if (out1 && out2) {
74+
continue;
75+
}
76+
77+
if (out1 || out2) {
78+
return current.count + 1;
79+
}
80+
81+
if (board[nx1][ny1] == '#') {
82+
nx1 = current.x1;
83+
ny1 = current.y1;
84+
}
85+
if (board[nx2][ny2] == '#') {
86+
nx2 = current.x2;
87+
ny2 = current.y2;
88+
}
89+
90+
String stateKey = nx1 + "," + ny1 + "," + nx2 + "," + ny2;
91+
92+
if (!visited.contains(stateKey)) {
93+
visited.add(stateKey);
94+
queue.offer(new State(nx1, ny1, nx2, ny2, current.count + 1));
95+
}
96+
}
97+
}
98+
99+
return -1;
100+
}
101+
102+
static boolean isOutOfBounds(int x, int y) {
103+
return x < 0 || x >= N || y < 0 || y >= M;
104+
}
105+
}
106+
```

0 commit comments

Comments
 (0)