문제링크 : https://www.acmicpc.net/problem/4963

 

4963번: 섬의 개수

문제 정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오. 한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사

www.acmicpc.net

 문제설명 

 

 맵에서 1은 섬을 나타내고 0은 바다를 나타낸다 섬은 상하좌우 대각선 총 8방향으로 이어져있을때,

 주어진 배열의 섬의 갯수를 구하여라.

 

 알고리즘 

 

1. DFS 를 이용하여 8방향을 탐색 하여 컴포넌트의 갯수를 출력한다.

 

 코드 

 

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
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
using namespace std;
 
 
 
int map[51][51];
int visited[51][51];
int dy[8= { 1,-1,0,0,1,1,-1,-1 };
int dx[8= { 0,0,1,-1,1,-1,- 1,1 };
int w, h;
 
void dfs(int y, int x) {
    if (visited[y][x]) return;
 
    visited[y][x] = 1;
 
    //8방향 탐색
    for (int i = 0; i < 8; i++) {
        int next_x = x + dx[i];
        int next_y = y + dy[i];
 
        //배열 경계
        if (next_x >= 0 && next_y >= 0 && next_y < h && next_x < w) {
            if (!visited[next_y][next_x] && map[next_y][next_x]) {
                dfs(next_y, next_x);
            }
        }
    }
}
 
// 초기화 함수
void reset(int y, int x) {
    for (int i = 0; i < y; i++) {
        for (int j = 0; j < x; j++) {
            map[i][j] = 0;
            visited[i][j] = 0;
        }
    }
 
}
int main() {
 
    while (1) {
        cin >> w >> h;
        if (w == 0 && h == 0)break;
 
        //지도입력
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                cin >> map[i][j];
            }
        }
 
        int cnt = 0;
 
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                if (map[i][j] && !visited[i][j]) {
                    dfs(i, j);
                    cnt++;
                }
            }
        }
 
        cout << cnt << endl;
        reset(h, w);
    }
}
 
cs

'c++ > 백준' 카테고리의 다른 글

백준 10159번 : 저울  (0) 2020.05.22
백준 1431번 : 시리얼 번호  (0) 2020.05.22
백준 6603번: 로또  (0) 2020.05.22
백준 1181번: 단어 정렬  (0) 2020.05.22
백준 3055번 : 탈출  (0) 2020.05.07
ariz1623