Skip to content

Commit 9f53554

Browse files
authored
[20251107] PGM / LV2 / 무인도 여행 / 강신지
1 parent 82d3d42 commit 9f53554

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
```java
2+
import java.util.*;
3+
4+
class Solution {
5+
static final int[] dx = {1,-1,0,0};
6+
static final int[] dy = {0,0,1,-1};
7+
8+
public int[] solution(String[] maps) {
9+
int n = maps.length;
10+
int m = maps[0].length();
11+
boolean[][] visited = new boolean[n][m];
12+
List<Integer> ans = new ArrayList<>();
13+
14+
for (int i = 0; i < n; i++) {
15+
for (int j = 0; j < m; j++) {
16+
if (maps[i].charAt(j) == 'X' || visited[i][j]) continue;
17+
18+
int sum = 0;
19+
ArrayDeque<int[]> q = new ArrayDeque<>();
20+
q.offer(new int[]{i, j});
21+
visited[i][j] = true;
22+
23+
while (!q.isEmpty()) {
24+
int[] cur = q.poll();
25+
int y = cur[0], x = cur[1];
26+
sum += maps[y].charAt(x) - '0';
27+
28+
for (int d = 0; d < 4; d++) {
29+
int ny = y + dy[d], nx = x + dx[d];
30+
if (ny < 0 || nx < 0 || ny >= n || nx >= m) continue;
31+
if (visited[ny][nx] || maps[ny].charAt(nx) == 'X') continue;
32+
visited[ny][nx] = true;
33+
q.offer(new int[]{ny, nx});
34+
}
35+
}
36+
ans.add(sum);
37+
}
38+
}
39+
40+
if (ans.isEmpty()) return new int[]{-1};
41+
Collections.sort(ans);
42+
return ans.stream().mapToInt(Integer::intValue).toArray();
43+
}
44+
}
45+
46+
```

0 commit comments

Comments
 (0)