๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 11724๋ฒˆ - ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜

by dkswnkk 2021. 10. 31.
 

11724๋ฒˆ: ์—ฐ๊ฒฐ ์š”์†Œ์˜ ๊ฐœ์ˆ˜

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N๊ณผ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฐ„์„ ์˜ ์–‘ ๋์  u์™€ v๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ u, v ≤ N, u ≠ v) ๊ฐ™์€ ๊ฐ„์„ ์€ ํ•œ ๋ฒˆ๋งŒ ์ฃผ

www.acmicpc.net

#include <iostream>
#include <queue>

using namespace std;

int map[1001][1001];
int visited[1001];
int cnt = 0;
int N, M;

void dfs(int x) {
    visited[x] = 1;

    for (int i = 1; i <=N; i++) {
        if (!visited[i] && map[x][i]) {
            visited[i] = 1;
            dfs(i);
        }
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> N>>M;

    for (int i = 0; i < M; i++) {
        int a, b;
        cin >> a >> b;
        map[a][b] = map[b][a] = 1;    //์—ฐ๊ฒฐ์š”์†Œ ์ž…๋ ฅ
    }
    for (int i = 1; i <= N; i++) {
        if (!visited[i]) {
            dfs(i);
            cnt++;
        }
    }

    cout << cnt;
}

๋Œ“๊ธ€