// 📘 문제 1: 숫자 영역 개수 구하기

// N×M 크기의 지도에서
// 1은 땅, 0은 바다이다.

// 상, 하, 좌, 우로 연결된 1의 덩어리 개수를 구하시오.

// (대각선은 연결되지 않음)

// 입력 예시
// 5 5
// 1 1 0 0 0
// 1 0 0 1 1
// 0 0 0 1 1
// 0 1 0 0 0
// 0 1 1 0 0
// 출력 예시
// 4


#include <iostream>
using namespace std;

int n, m;
int map[50][50];
bool visited[50][50];

int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};

void dfs(int x, int y) {

    visited[x][y] = true;

    for(int i = 0; i < 4; i++) {

        int nx = x + dx[i];
        int ny = y + dy[i];

        // 범위 확인
        if(nx >= 0 && nx < n && ny >= 0 && ny < m) {

            // 아직 방문 안했고 1이면
            if(!visited[nx][ny] && map[nx][ny] == 1) {

                dfs(nx, ny);

            }

        }

    }

}

int main() {

    cin >> n >> m;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
            cin >> map[i][j];
        }
    }

    int count = 0;

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {

            if(!visited[i][j] && map[i][j] == 1) {

                dfs(i, j);
                count++;

            }

        }
    }

    cout << count;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: