dfs, bfs 원하는거 쓰면 된다.


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
#include <stdio.h>
 
int a[51][51], ans, w, h, tc;
int dx[] = { -1,-1,-1,0,1,1,1,0 };
int dy[] = { -1,0,1,1,1,0,-1,-1 };
 
void dfs(int x, int y) {
    a[x][y] = 0;
    for (int i = 0; i < 8; i++) {
        int nx = x + dx[i], ny = y + dy[i];
        if (nx < 0 || ny < 0 || nx >= h || ny >= w || a[nx][ny] == 0continue;
        dfs(nx, ny);
    }
}
 
void scaner() {
    for (int i = 0; i < h; i++for (int j = 0; j < w; j++)
        scanf(" %1d"&a[i][j]);
}
 
void dfser() {
    for (int i = 0; i < h; i++for (int j = 0; j < w; j++)
        if (a[i][j]) {
            ans++;
            dfs(i, j);
        }
}
 
int main() {
    while (1) {
        scanf(" %d %d"&w, &h);
        if (w == 0 && h == 0break;
        ans = 0;
        scaner();
        dfser();
        printf("%d\n", ans);
    }
    return 0;
}
cs


'BOJ' 카테고리의 다른 글

1072 게임  (0) 2018.02.18
11559 Puyo Puyo  (0) 2018.02.18
11812 K진 트리  (0) 2018.02.18
1761 정점들의 거리  (0) 2018.02.17
11437 LCA  (0) 2018.02.17

+ Recent posts