55
66public class _11123 {
77
8- static int h , w ;
9- static char [][] graph ;
10- static boolean [][] visited ;
11- static int [] dx = {1 , 0 , -1 , 0 };
12- static int [] dy = {0 , 1 , 0 , -1 };
8+ private static int h ;
9+ private static int w ;
1310
14- public static void dfs (int x , int y ) {
11+ private static char [][] graph ;
12+ private static boolean [][] visited ;
1513
16- for (int i = 0 ; i < 4 ; i ++) {
17- int x1 = dx [i ] + x ;
18- int y1 = dy [i ] + y ;
19-
20- // 그리드의 범위를 벗어났을 때
21- if (x1 < 0 || y1 < 0 || x1 >= h || y1 >= w ) {
22- continue ;
23- }
24-
25- // # 이면서 방문하지 않았을 때
26- if (graph [x1 ][y1 ] == '#' && !visited [x1 ][y1 ]) {
27- visited [x1 ][y1 ] = true ;
28- dfs (x1 , y1 );
29- }
30- }
31-
32- }
14+ private static int [] dx = {-1 , 1 , 0 , 0 };
15+ private static int [] dy = {0 , 0 , -1 , 1 };
3316
3417 public static void main (String [] args ) throws IOException {
3518 BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
3619 BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (System .out ));
3720 StringBuilder sb = new StringBuilder ();
3821 StringTokenizer st ;
3922
40- int testCase = Integer .parseInt (br .readLine ());
23+ int testCases = Integer .parseInt (br .readLine ());
4124
42- while (testCase -- > 0 ) {
25+ while (testCases -- > 0 ) {
4326 st = new StringTokenizer (br .readLine ());
4427
4528 h = Integer .parseInt (st .nextToken ());
@@ -49,23 +32,21 @@ public static void main(String[] args) throws IOException {
4932 visited = new boolean [h ][w ];
5033
5134 for (int i = 0 ; i < h ; i ++) {
52- String input = br .readLine ();
35+ String str = br .readLine ();
5336
5437 for (int j = 0 ; j < w ; j ++) {
55- graph [i ][j ] = input .charAt (j );
38+ graph [i ][j ] = str .charAt (j );
5639 }
5740 }
41+
5842 int count = 0 ;
5943
6044 for (int i = 0 ; i < h ; i ++) {
6145 for (int j = 0 ; j < w ; j ++) {
62-
63- // # 이면서 방문하지 않았을 때, dfs 탐색
64- if (graph [i ][j ] == '#' && !visited [i ][j ]) {
46+ if (!visited [i ][j ] && graph [i ][j ] == '#' ) {
6547 dfs (i , j );
6648 count ++;
6749 }
68-
6950 }
7051 }
7152
@@ -76,4 +57,21 @@ public static void main(String[] args) throws IOException {
7657 bw .flush ();
7758 bw .close ();
7859 }
60+
61+ private static void dfs (int x , int y ) {
62+ for (int i = 0 ; i < 4 ; i ++) {
63+ int nx = x + dx [i ];
64+ int ny = y + dy [i ];
65+
66+ if (nx < 0 || ny < 0 || nx >= h || ny >= w ) {
67+ continue ;
68+ }
69+
70+ if (!visited [nx ][ny ] && graph [nx ][ny ] == '#' ) {
71+ visited [nx ][ny ] = true ;
72+ dfs (nx , ny );
73+ }
74+ }
75+ }
76+
7977}
0 commit comments