-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path백인찬.java
92 lines (82 loc) · 3.06 KB
/
백인찬.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.*;
import java.util.*;
public class Main {
static int N, M, iceCount = 0;
static int[][] map, seaCount;
// 상 하 좌 우
static final int[] mx = {0, 0, -1, 1};
static final int[] my = {-1, 1, 0, 0};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
map = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if (map[i][j] != 0) iceCount++;
}
}
int year = 0;
while(bfs()) year++;
if(iceCount == 0) bw.write("0\n");
else bw.write(year + "\n");
bw.flush();
bw.close();
}
static boolean bfs() {
Queue<int[]> q = new LinkedList<>();
boolean[][] visited = new boolean[N][M];
seaCount = new int[N][M];
int chunkCount = 0, steps = 0;
boolean flag = false;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(map[i][j] != 0 && !visited[i][j]) {
chunkCount++;
if(chunkCount >= 2) return false;
q.add(new int[]{i, j});
visited[i][j] = true;
while(!q.isEmpty()) {
int[] cur = q.remove();
int count = 0;
for (int k = 0; k < 4; k++) {
int ty = cur[0] + my[k];
int tx = cur[1] + mx[k];
if (ty >= 0 && ty < N && tx >= 0 && tx < M) {
if(!visited[ty][tx]) {
if(map[ty][tx] == 0) count++;
else {
visited[ty][tx] = true;
q.add(new int[]{ty, tx});
steps++;
}
}
}
}
seaCount[cur[0]][cur[1]] = count;
}
}
if(steps == iceCount) {
flag = true;
break;
}
}
if(flag) break;
}
iceCount = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if(map[i][j] != 0) {
map[i][j] = Math.max(0, map[i][j] - seaCount[i][j]);
if(map[i][j] != 0) iceCount++;
}
}
}
return iceCount != 0;
}
}