์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 2667๋ฒˆ: ๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ (DFS/BFS, C++)

PROGRAMMING/Algorithm

by koharin 2021. 2. 27. 00:06

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


N x N ํฌ๊ธฐ์˜ ์ง€๋„์—์„œ ์ง‘์€ 1๋กœ ํ‘œ์‹œ๋œ๋‹ค.

๋Œ€๊ฐ์„ ์€ ๊ฐ™์€ ๋‹จ์ง€๋กœ ์ทจ๊ธ‰ํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ƒ, ํ•˜, ์ขŒ, ์šฐ์˜ ๊ฒฝ์šฐ๋งŒ ๊ฐ™์€ ๋‹จ์ง€์ด๋‹ค.

์ถœ๋ ฅ: ๋‹จ์ง€ ์ˆ˜, ๊ฐ ๋‹จ์ง€๋ณ„ ์ง‘์˜ ์ˆ˜๋ฅผ ํ•œ ์ค„ ์”ฉ ์ถœ๋ ฅํ•œ๋‹ค.

current ์ขŒํ‘œ ๊ธฐ์ค€ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋ฅผ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๊ณ , ์ขŒํ‘œ๊ฐ€ 0๋ณด๋‹ค ํฌ๊ณ  N๋ณด๋‹ค ์ž‘์œผ๋ฉฐ (์ขŒํ‘œ์—์„œ ๋ฒ—์–ด๋‚˜์ง€ ์•Š์Œ) 1์˜ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฉด count++์„ ํ•˜๊ณ , ์žฌ๊ท€๊ฐ€ ๋๋‚˜๊ณ  ์ฒ˜์Œ ํ˜ธ์ถœํ–ˆ๋˜ ํ•จ์ˆ˜๋กœ ๋ฆฌํ„ดํ•˜๋ฉด ํ•ด๋‹น count๋ฅผ deque์— ์ถ”๊ฐ€ํ•œ๋‹ค.

์™„๋ฃŒ ํ›„, result์— ์žˆ๋Š” ๊ฑธ sort๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ ํ›„ ์ถœ๋ ฅํ•œ๋‹ค.

 

 

๐Ÿ’ป C++ ์ œ์ถœ์ฝ”๋“œ


#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

int cnt;
int graph[25][25];
bool visited[25][25];
int dx[] = {-1, 0, 1, 0}; int dy[] = {0, 1, 0, -1};
void DFS(int x, int y, int N){
    cnt++;
    visited[x][y] = true;
    for(int i=0; i<4; i++){
        int nx = x + dx[i]; int ny = y + dy[i];
        if(nx < 0 || ny < 0 || nx >=N || ny >= N) continue;
        if(graph[nx][ny] == 1 && !visited[nx][ny]) DFS(nx, ny, N);
    }
}

int main(){ 
    int N;
    scanf("%d", &N);
    deque<int> result;

    for(int i=0; i<N; i++){
        string s; cin >> s;
        for(int j=0; j<N; j++) graph[i][j] = s[j]-'0';
    }
    for(int i=0; i<N; i++){
        for(int j=0; j<N; j++){
            if(graph[i][j] == 1 && !visited[i][j]) { 
                cnt = 0;
                DFS(i, j, N); 
                result.push_back(cnt);
            }
        }
    }
    sort(result.begin(), result.end());
    printf("%d\n", result.size());
    for(int n: result) printf("%d\n", n);
}

 

 

๐Ÿ‘ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ