2667 단지번호붙이기

2020. 2. 4. 13:27Learn/Algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
 
import java.util.Scanner;
 
public class Main {
    static int[] dx = {0,0,1,-1};
    static int[] dy = {1,-1,0,0};
    static int test;
    static int cnt;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        test = sc.nextInt();
        int arr[][] = new int [test][test];
        boolean arr2[][] = new boolean [test][test];
        ArrayList<Integer> al = new ArrayList<>();
        String s;
        for(int i = 0; i < test; i++) {
            s = sc.next();
            for(int j = 0; j < test; j++) {
                 arr[i][j] = s.charAt(j) - '0';
            }    
        }
        for(int i = 0; i < test; i++) {
            for(int j = 0; j < test; j++) {
                if(arr[i][j] == 1) {
                    cnt = 0;
                    DFS(i,j,cnt,arr,arr2);
                    if(cnt != 0)
                        al.add(cnt);
                }
            }
        }
        al.sort(Comparator.naturalOrder());
        System.out.println(al.size());
        for(int i = 0; i < al.size(); i++) {
            System.out.println(al.get(i));
        }
    }
    public static void DFS(int n,int w,int c,int ar[][],boolean ar2[][]) {
        if(ar2[n][w] == false)
            cnt++;
        ar2[n][w] = true;
        for(int i = 0; i < 4; i++) {
            int nn = n + dx[i];
            int ww = w + dy[i];
            if(nn >= 0 && nn < test && ww >= 0 && ww < test ) {
                if(ar2[nn][ww] == true)
                    continue;
                if(ar[nn][ww] == 1) {
                    DFS(nn,ww,cnt,ar,ar2);
                }
            }
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

DFS + 사방탐색 문제 

DFS구현만 하면 간단

'Learn > Algorithm' 카테고리의 다른 글

2178번 미로 탐색  (0) 2020.02.04
1012 유기농 배추  (0) 2020.02.04
1260 DFS 와 BFS - 백준  (0) 2020.02.04
14720 우유축제  (0) 2020.02.03
1003번 피보나치 함수  (0) 2020.02.03