반응형
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 | #include <iostream> #include <queue> #include <algorithm> using namespace std; int d[51][51],a[51][51], cnt, dx[] = {0,0,-1,1,1,1,-1,-1}, dy[] = {-1,1,0,0,1,-1,1,-1 },w,h; void BFS(int x, int y, int cnt) { queue <pair<int, int> > q; q.push(make_pair(x, y)); d[x][y] = cnt; while (!q.empty()) { x = q.front().first; y = q.front().second; q.pop(); for (int i = 0; i < 8; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (0 <= nx && nx < h && 0 <= ny && ny < w) if (d[nx][ny] == 0 && a[nx][ny] == 1) { q.push(make_pair(nx, ny)); d[nx][ny] = cnt; } } } } int main() { while (1) { cin >> w >> h; if (w == 0 && h == 0) { return 0; } cnt = 0; for (int i = 0; i < 51; i++)//초기화 for (int j = 0; j < 51; j++) a[i][j] = d[i][j] = 0; for (int i = 0; i < h; i++)//입력 for (int j = 0; j < w; j++) cin >> a[i][j]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) if (a[i][j] == 1 && d[i][j] == 0) BFS(i, j, ++cnt); cout << cnt << '\n'; } } | cs |
'Algorithm' 카테고리의 다른 글
(C++) - 백준(BOJ) 13241번 : 최소공배수 답 (0) | 2017.02.10 |
---|---|
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 4963번:섬의 개수(DFS) 답 (0) | 2017.02.08 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2693번:N번째 큰 수 답 (0) | 2017.02.08 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 1932번:숫자삼각형 답 (0) | 2017.02.08 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2667번:단지번호붙이기(DFS) 답 (0) | 2017.02.08 |