Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Seol-JY/202507/18 G4 두 동전.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
```java
import java.io.*;
import java.util.*;

public class Main {
static int N, M;
static char[][] board;
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};

static class State {
int x1, y1, x2, y2, count;

State(int x1, int y1, int x2, int y2, int count) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.count = count;
}
}

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());

N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());

board = new char[N][M];
List<int[]> coins = new ArrayList<>();

for (int i = 0; i < N; i++) {
String line = br.readLine();
for (int j = 0; j < M; j++) {
board[i][j] = line.charAt(j);
if (board[i][j] == 'o') {
coins.add(new int[]{i, j});
board[i][j] = '.';
}
}
}

int result = bfs(coins.get(0)[0], coins.get(0)[1],
coins.get(1)[0], coins.get(1)[1]);

System.out.println(result);
}

static int bfs(int x1, int y1, int x2, int y2) {
Queue<State> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();

queue.offer(new State(x1, y1, x2, y2, 0));
visited.add(x1 + "," + y1 + "," + x2 + "," + y2);

while (!queue.isEmpty()) {
State current = queue.poll();

if (current.count >= 10) {
continue;
}

for (int dir = 0; dir < 4; dir++) {
int nx1 = current.x1 + dx[dir];
int ny1 = current.y1 + dy[dir];
int nx2 = current.x2 + dx[dir];
int ny2 = current.y2 + dy[dir];

boolean out1 = isOutOfBounds(nx1, ny1);
boolean out2 = isOutOfBounds(nx2, ny2);

if (out1 && out2) {
continue;
}

if (out1 || out2) {
return current.count + 1;
}

if (board[nx1][ny1] == '#') {
nx1 = current.x1;
ny1 = current.y1;
}
if (board[nx2][ny2] == '#') {
nx2 = current.x2;
ny2 = current.y2;
}

String stateKey = nx1 + "," + ny1 + "," + nx2 + "," + ny2;

if (!visited.contains(stateKey)) {
visited.add(stateKey);
queue.offer(new State(nx1, ny1, nx2, ny2, current.count + 1));
}
}
}

return -1;
}

static boolean isOutOfBounds(int x, int y) {
return x < 0 || x >= N || y < 0 || y >= M;
}
}
```