File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ class Solution {
3+ static int [][] array ;
4+ static boolean [][] visit ;
5+ static int n ,m ;
6+ static int result ;
7+ public int [] solution (String [] maps ) {
8+
9+
10+ n = maps .length ;
11+ m = maps [0 ].length ();
12+ visit = new boolean [maps .length ][maps [0 ].length ()];
13+ array = new int [maps .length ][maps [0 ].length ()];
14+ for (int i = 0 ; i < maps .length ;i ++) {
15+ for (int j = 0 ;j < maps [i ].length ();j ++) {
16+ if (maps [i ].charAt (j ) != 'X' ) {
17+ array [i ][j ] = maps [i ].charAt (j ) - '0' ;
18+ }
19+ }
20+ }
21+
22+ List <Integer > list = new ArrayList <>();
23+ for (int i = 0 ; i < maps .length ;i ++) {
24+ for (int j = 0 ;j < maps [i ].length ();j ++) {
25+ if (!visit [i ][j ] && array [i ][j ] != 0 ) {
26+ result = 0 ;
27+ dfs (i ,j );
28+ list .add (result );
29+ }
30+ }
31+ }
32+ if (list .size () == 0 ) {
33+ int [] answer = {-1 };
34+ return answer ;
35+ } else {
36+ int [] answer = new int [list .size ()];
37+ for (int i = 0 ;i < list .size ();i ++) {
38+ answer [i ] = list .get (i );
39+ }
40+ Arrays .sort (answer );
41+ return answer ;
42+ }
43+
44+
45+
46+ }
47+
48+ public void dfs (int x ,int y ) {
49+ visit [x ][y ] = true ;
50+ result += array [x ][y ];
51+ int [] dx = {1 ,-1 ,0 ,0 };
52+ int [] dy = {0 ,0 ,1 ,-1 };
53+ for (int i = 0 ;i < 4 ;i ++) {
54+ int cx = x + dx [i ];
55+ int cy = y + dy [i ];
56+ if (cx >= 0 && cy >= 0 && cx < n && cy < m && !visit [cx ][cy ] && array [cx ][cy ] != 0 ) {
57+ dfs (cx ,cy );
58+ }
59+ }
60+ }
61+ }
You can’t perform that action at this time.
0 commit comments