Skip to content

Commit 3333682

Browse files
authored
Merge pull request #450 from AlgorithmWithGod/LiiNi-coder
[20250712] BOJ / G5 / 토마토 / 이인희
2 parents 40119d2 + 8f851b9 commit 3333682

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
```java
2+
import java.awt.Point;
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.ArrayDeque;
7+
import java.util.HashMap;
8+
import java.util.HashSet;
9+
import java.util.StringTokenizer;
10+
11+
public class B7576 {
12+
private static BufferedReader br;
13+
private static ArrayDeque<IntAndPoint> q;
14+
private static StringTokenizer st;
15+
private static HashSet<Point> wall_tomato_set;
16+
private static int[][] drdcs = {
17+
{1, 0},
18+
{0, -1},
19+
{-1, 0},
20+
{0, 1}
21+
};
22+
23+
private static class IntAndPoint{
24+
Point p; int level;
25+
public IntAndPoint(Point p, int level) {
26+
this.p = p;
27+
this.level = level;
28+
}
29+
}
30+
31+
public static void main(String[] args) throws IOException {
32+
br = new BufferedReader(new InputStreamReader(System.in));
33+
34+
//입력
35+
int n, m;
36+
String[] temp = br.readLine().split(" ");
37+
m = Integer.parseInt(temp[0]);
38+
n = Integer.parseInt(temp[1]);
39+
q = new ArrayDeque<IntAndPoint>();
40+
wall_tomato_set = new HashSet<Point>();
41+
for(int r=0; r<n; r++) {
42+
st = new StringTokenizer(br.readLine());
43+
for(int c = 0; c<m; c++) {
44+
int value = Integer.parseInt(st.nextToken());
45+
if(value==1) {
46+
q.add(new IntAndPoint(new Point(r, c), 0));
47+
}else if(value == -1)
48+
wall_tomato_set.add(new Point(r, c));
49+
}
50+
}
51+
52+
int max_level = 0;
53+
// bfs 진행
54+
while(!q.isEmpty()) {
55+
var temp1 = q.pollFirst();
56+
Point p = temp1.p;
57+
wall_tomato_set.add(p);
58+
int level = temp1.level;
59+
max_level = Math.max(max_level, level);
60+
61+
for(int[] drdc : drdcs) {
62+
Point next_p = new Point(p.x + drdc[0], p.y + drdc[1]);
63+
//범위체크
64+
if(next_p.x <0 || next_p.x >= n || next_p.y <0 || next_p.y >= m) {
65+
continue;
66+
}
67+
// 벽인지와 토마토인지 확인
68+
if(wall_tomato_set.contains(next_p))
69+
continue;
70+
q.addLast(new IntAndPoint(next_p, level+1));
71+
}
72+
}
73+
74+
// 만약 벽 또는 토마토의 개수가 n*m개수와 다르면 불가능
75+
if(wall_tomato_set.size() != n*m) {
76+
System.out.println(-1);
77+
}else {
78+
System.out.println(max_level);
79+
}
80+
br.close();
81+
}
82+
83+
}
84+
```

0 commit comments

Comments
 (0)