File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments