Skip to content

Commit edca1d8

Browse files
authored
[20251007] PGM / Lv2 / 석유 시추 / 김수연
[20251007] PGM / Lv2 / 석유 시추 / 김수연
2 parents bc8e4b9 + 5c252d4 commit edca1d8

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
```java
2+
import java.util.*;
3+
class Solution {
4+
static int[][] visited;
5+
static int[][] dir = new int[][] {{1,0},{-1,0},{0,1},{0,-1}};
6+
static int N, M, answer;
7+
8+
static int id;
9+
static int[] size;
10+
11+
public int solution(int[][] land) {
12+
answer = 0;
13+
N = land.length;
14+
M = land[0].length;
15+
visited = new int[N][M];
16+
size = new int[N * M + 1];
17+
id = 0;
18+
19+
// 0 : 빈 땅, 1 : 석유가 있는 땅
20+
for (int j = 0; j < M; j++) {
21+
int total = 0;
22+
Set<Integer> used = new HashSet<>();
23+
for (int i = 0; i < N; i++) {
24+
if (land[i][j] == 0) continue;
25+
if (visited[i][j] == 0) {
26+
id++;
27+
bfs(i, j, land);
28+
}
29+
int comp = visited[i][j];
30+
if (!used.contains(comp)) {
31+
used.add(comp);
32+
total += size[comp];
33+
}
34+
int ny = i;
35+
while (i < N && land[i][j] == 1) i++;
36+
if (i != N) i--;
37+
}
38+
answer = Math.max(answer, total);
39+
}
40+
return answer;
41+
}
42+
43+
private void bfs(int i, int j, int[][] land) {
44+
Queue<Point> q = new LinkedList<>();
45+
q.add(new Point(i, j));
46+
visited[i][j] = -1;
47+
int maxVal = 1;
48+
49+
while (!q.isEmpty()) {
50+
Point cur = q.poll();
51+
for (int[] d : dir) {
52+
int ny = cur.y + d[0];
53+
int nx = cur.x + d[1];
54+
if (ny < 0 || ny >= N || nx < 0 || nx >= M) continue;
55+
if (land[ny][nx] == 0 || visited[ny][nx] != 0) continue;
56+
q.add(new Point(ny, nx));
57+
visited[ny][nx] = -1;
58+
maxVal++;
59+
}
60+
}
61+
62+
q.add(new Point(i, j));
63+
visited[i][j] = id;
64+
while (!q.isEmpty()) {
65+
Point cur = q.poll();
66+
for (int[] d : dir) {
67+
int ny = cur.y + d[0];
68+
int nx = cur.x + d[1];
69+
if (ny < 0 || ny >= N || nx < 0 || nx >= M) continue;
70+
if (visited[ny][nx] != -1) continue;
71+
q.add(new Point(ny, nx));
72+
visited[ny][nx] = id;
73+
}
74+
}
75+
size[id] = maxVal;
76+
}
77+
78+
static class Point {
79+
int y, x;
80+
public Point(int y, int x) {
81+
this.y = y;
82+
this.x = x;
83+
}
84+
}
85+
}
86+
```

0 commit comments

Comments
 (0)