-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbaekjoon_7576.java
More file actions
64 lines (53 loc) · 1.54 KB
/
baekjoon_7576.java
File metadata and controls
64 lines (53 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.io.*;
import java.util.*;
public class baekjoon_7576 {
static int[] dr = {-1, 1, 0, 0};
static int[] dc = {0, 0, -1, 1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
final int M = Integer.parseInt(st.nextToken());
final int N = Integer.parseInt(st.nextToken());
int[][] board = new int[N][M];
int[][] day = new int[N][M];
for (int r = 0; r < N; r++) Arrays.fill(day[r], -1);
Deque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < N; r++) {
st = new StringTokenizer(br.readLine());
for (int c = 0; c < M; c++) {
int v = Integer.parseInt(st.nextToken());
board[r][c]= v;
if (v == 1) { // 익은 놈
day[r][c] = 0; // 0일부터 시작
q.offer(new int[] {r, c});
}
}
}
while (!q.isEmpty()) {
int[] cur = q.poll();
int r = cur[0];
int c = cur[1];
for (int i = 0; i < 4; i++) {
int nr = r + dr[i];
int nc = c + dc[i];
if (nr < 0 || nr >= N || nc < 0 || nc >= M) continue;
if (board[nr][nc] == -1) continue; // 빈 칸
if (day[nr][nc] != -1) continue; // 이미 방문
day[nr][nc] = day[r][c] + 1;
q.offer(new int[] {nr, nc});
}
}
int ans = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (board[i][j] == -1) continue;
if (day[i][j] == -1) {
System.out.println(-1);
return;
}
ans = Math.max(ans, day[i][j]);
}
}
System.out.println(ans);
}
}