안선생의 개발 블로그

C++ 섬의 개수 본문

백준

C++ 섬의 개수

안선생 2023. 2. 17. 17:56
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <iostream>
#include <vector>
#include<queue>
#include<algorithm>
using namespace std;
 
 
int g[52][52= {};
bool visit[52][52= {};
int n=1,m=1,k;
int dx[8= { 0,1,0,-1 ,1,-1,-1,1};
int dy[8= { 1,0,-1,0 ,1,-1,1,-1};
void dfs(int x, int y)
{
    visit[x][y] = 1;
 
    for (int i = 0; i < 8; i++)
    {
        int xx = x + dx[i];
        int yy = y + dy[i];
        if (xx < 0 || xx >= m || yy < 0 || yy >= n || !g[xx][yy])
            continue;
        if (!visit[xx][yy] && g[xx][yy])
        {
            dfs(xx, yy);
        }
    }
}
void bfs(int x,int y)
{
    queue<pair<int,int>> a;
    a.push({ x,y });
    while (!a.empty())
    {
        int xx = a.front().first;
        int yy = a.front().second;
        a.pop();
        for (int i = 0; i <8; i++)
        {
            int x1 = xx + dx[i];
            int y1 = yy + dy[i];
            
            if (x1 < 0 || x1 >=|| y1 < 0 || y1 >= n|| !g[x1][y1])
                continue;
            if(!visit[x1][y1])
            {              
                a.push({ x1,y1 });       
                visit[x1][y1] = 1;
            }
 
        }
    }
 
}
void reset()
{
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            g[i][j] = 0;
            visit[i][j] = 0;
        }
     }
}
int main(void)
{
   
   
    while (1)
    {
        cin >> n >> m;
        if (!&& !m)
            break;
        int result = 0;
 
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
               
                cin >> g[i][j];
            }
        }
 
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                if (!visit[i][j] && g[i][j])
                {
                    bfs(i, j);
                    result++;
                }
            }
        }
        cout << result << "\n";
        reset();
    
    }
  
    return 0;
}
cs

https://www.acmicpc.net/problem/4963

 

4963번: 섬의 개수

입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도

www.acmicpc.net

 

'백준' 카테고리의 다른 글

C++ 7652 나이트의 이동  (0) 2023.02.18
C++ 10026 적록색약  (0) 2023.02.17
C++ 1012 유기농 배추  (0) 2023.02.16
C++ 2178 미로 탐색  (0) 2023.02.16
C++ 24445 알고리즘 수업 - 너비 우선 탐색 2  (0) 2023.02.16