-
Notifications
You must be signed in to change notification settings - Fork 0
/
2573(BFS).java
126 lines (105 loc) · 3.51 KB
/
2573(BFS).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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import java.util.*;
import java.io.*;
public class Main{
static int origin[][], temp[][];
static int N, M;
static boolean visited[][];
static int dx[] = {0, 0, 1, -1};
static int dy[] = {1, -1, 0, 0};
public static void bfs(int x, int y) {
Queue<Pair> queue = new LinkedList<>();
queue.add(new Pair(x, y));
visited[x][y] = true;
while (!queue.isEmpty()){
Pair current = queue.remove();
int currentX = current.x;
int currentY = current.y;
for(int i = 0; i < 4; i++) {
int nextX = currentX + dx[i];
int nextY = currentY + dy[i];
if(nextX < 0 || nextY < 0 || nextX >= N || nextY >= M){
continue;
}
if(visited[nextX][nextY]){
continue;
}
if(origin[nextX][nextY] != 0 && !visited[nextX][nextY]){
visited[nextX][nextY] = true;
queue.add(new Pair(nextX, nextY));
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
origin = new int[N][M];
temp = new int[N][M];
visited = new boolean[N][M];
for(int i = 0; i < N; i++){
st = new StringTokenizer(br.readLine());
for(int j = 0; j < M; j++) {
origin[i][j] = Integer.parseInt(st.nextToken());
}
} //input end
int answer = 0;
while (true) {
int count = 0;
boolean flag = false;
int check = 0;
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(origin[i][j] != 0){
check++;
}
if(origin[i][j] != 0 && !visited[i][j]){
count++;
flag = true;
bfs(i, j);
}
}
}
if(!flag || count > 1 || check == 1){
if(!flag){
answer = 0;
}
break;
}
answer++;
temp = new int[N][M];
visited = new boolean[N][M];
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
if(origin[i][j] != 0){
int zerocount = 0;
for(int x = 0; x < 4; x++){
int nextX = i + dx[x];
int nextY = j + dy[x];
if(nextX < 0 || nextY < 0 || nextX >= N || nextY >= M){
continue;
}
if(origin[nextX][nextY] == 0){
zerocount++;
}
}
temp[i][j] = Math.max((origin[i][j] - zerocount), 0);
}
}
} // 빙하 녹이기
origin = temp;
}
System.out.println(answer);
}
}
class Pair{
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}