Skip to content

Commit e0d2271

Browse files
authored
Merge pull request #627 from AlgorithmWithGod/JHLEE325
[20250808] BOJ / G4 /뱀 / 이준희
2 parents 4f98d1f + 664af86 commit e0d2271

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

JHLEE325/202508/08 BOJ G4 뱀.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
7+
static int n, k, l;
8+
static int[][] board;
9+
static Deque<int[]> snake = new ArrayDeque<>();
10+
static Map<Integer, Character> dirMap = new HashMap<>();
11+
12+
static int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
13+
14+
public static void main(String[] args) throws Exception {
15+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
16+
StringTokenizer st;
17+
18+
n = Integer.parseInt(br.readLine());
19+
k = Integer.parseInt(br.readLine());
20+
board = new int[n][n];
21+
22+
for (int i = 0; i < k; i++) {
23+
st = new StringTokenizer(br.readLine());
24+
int r = Integer.parseInt(st.nextToken()) - 1;
25+
int c = Integer.parseInt(st.nextToken()) - 1;
26+
board[r][c] = 2;
27+
}
28+
29+
l = Integer.parseInt(br.readLine());
30+
for (int i = 0; i < l; i++) {
31+
st = new StringTokenizer(br.readLine());
32+
int t = Integer.parseInt(st.nextToken());
33+
char d = st.nextToken().charAt(0);
34+
dirMap.put(t, d);
35+
}
36+
37+
System.out.println(simulate());
38+
}
39+
40+
static int simulate() {
41+
int time = 0;
42+
int direction = 0;
43+
int x = 0, y = 0;
44+
45+
snake.offerLast(new int[]{y, x});
46+
board[y][x] = 1;
47+
48+
while (true) {
49+
time++;
50+
int dy = y + dir[direction][0];
51+
int dx = x + dir[direction][1];
52+
53+
if (!(0 <= dy && dy < n && 0 <= dx && dx < n) || board[dy][dx] == 1) break;
54+
55+
if (board[dy][dx] == 2) {
56+
board[dy][dx] = 1;
57+
snake.offerLast(new int[]{dy, dx});
58+
} else {
59+
board[dy][dx] = 1;
60+
snake.offerLast(new int[]{dy, dx});
61+
int[] tail = snake.pollFirst();
62+
board[tail[0]][tail[1]] = 0;
63+
}
64+
65+
if (dirMap.containsKey(time)) {
66+
char turn = dirMap.get(time);
67+
if (turn == 'L') direction = (direction + 3) % 4;
68+
else if (turn == 'D') direction = (direction + 1) % 4;
69+
}
70+
71+
y = dy;
72+
x = dx;
73+
}
74+
75+
return time;
76+
}
77+
78+
}
79+
80+
```

0 commit comments

Comments
 (0)