33class Solution {
44 int [] dx = {-1 ,1 ,0 ,0 };
55 int [] dy = {0 ,0 ,-1 ,1 };
6- boolean [][] visited = new boolean [101 ][101 ];
6+ boolean [][] visited ;
7+ int row ;
8+ int col ;
79
810 public int [] solution (String [] maps ) {
911 int [] start = new int [2 ];
10- int row = maps .length ;
11- int col = maps [0 ].length ();
12-
12+ row = maps .length ;
13+ col = maps [0 ].length ();
14+ visited = new boolean [ row ][ col ];
1315
1416 ArrayList <Integer > answer = new ArrayList <>();
1517 for (int i = 0 ; i < row ; i ++){
1618 String str = maps [i ];
1719 for (int j = 0 ; j < col ; j ++){
1820 char ch = str .charAt (j );
19- // 바다 나오면 pass
20- if (ch =='X' ) continue ;
21- if (visited [i ][j ]) continue ;
22-
23- start = new int [] {i ,j };
24- // 인접한 모든 섬 탐색
25- int sum = bfs (maps ,start ,ch );
26- answer .add (sum ); // 정답 리스트에 등록
21+ // 섬 or 방문한 적 없음
22+ if (ch !='X' && !visited [i ][j ]){
23+ start = new int [] {i ,j };
24+ int number = ch -'0' ;
25+ int sum = dfs (maps ,start ,number ); // DFS(깊이 우선 탐색)
26+ answer .add (sum ); // 정답 리스트에 등록
27+ }
2728 }
2829 }
2930 if (answer .isEmpty ()) return new int []{-1 };
@@ -34,38 +35,27 @@ public int[] solution(String[] maps) {
3435 .toArray ();
3536 }
3637
37- int bfs (String [] maps ,int [] start ,char ch ) {
38- int row = maps .length ;
39- int col = maps [0 ].length ();
40-
41- Queue <int []> queue = new LinkedList <>();
42- int number = ch -'0' ;
43- System .out .println ("number: " +number );
44-
38+ int dfs (String [] maps ,int [] start ,int number ) {
4539 visited [start [0 ]][start [1 ]] = true ;
46- queue .offer (new int []{start [0 ],start [1 ]});
4740
48- while (!queue .isEmpty ()) {
49- int [] current = queue .poll ();
50- int currentX = current [0 ]; // 0
51- int currentY = current [1 ]; // 1
52-
53- // 상하좌우 탐색
54- for (int i = 0 ; i < 4 ; i ++){
55- int nextX = currentX + dx [i ];
56- int nextY = currentY + dy [i ];
57- // 인접한 섬 발견
58- if (nextX >=0 && nextX <row && nextY >=0 && nextY <col && !visited [nextX ][nextY ]
59- && maps [nextX ].charAt (nextY ) != 'X' ){
60- int newNumber = maps [nextX ].charAt (nextY ) - '0' ;
61-
62- visited [nextX ][nextY ] = true ; // 방문 처리
63- queue .offer (new int []{nextX ,nextY }); // 큐에 등록
64- number += newNumber ; // 합
65- }
41+ int currentX = start [0 ];
42+ int currentY = start [1 ];
43+
44+ // 상하좌우 탐색
45+ for (int i = 0 ; i < 4 ; i ++){
46+ int nextX = currentX + dx [i ];
47+ int nextY = currentY + dy [i ];
48+ // 인접한 섬 발견
49+ if (nextX >=0 && nextX <row && nextY >=0 && nextY <col && !visited [nextX ][nextY ]
50+ && maps [nextX ].charAt (nextY ) != 'X' ){
51+ int newNumber = maps [nextX ].charAt (nextY ) - '0' ;
52+
53+ visited [nextX ][nextY ] = true ; // 방문 처리
54+ number += dfs (maps ,new int []{nextX ,nextY },newNumber ); // 합
6655 }
6756 }
6857
58+ System .out .println ("number: " +number );
6959 return number ;
7060 }
7161}
0 commit comments