Post

[BaekJoon] #11724 - 연결 요소의 개수 [Java][C++]

[BaekJoon] #11724 - 연결 요소의 개수 [Java][C++]

문제 링크


1. 아이디어

무방향 그래프에서 연결 요소의 개수를 구하는 문제로 BFS나 DFS를 활용해서 각 노드에 대해 방문하지 않았으면 모든 연결된 노드를 방문 처리하고 개수를 하나씩 세도 되며, 유니온 파인드 알고리즘을 활용해서 서로소 집합을 만든 후 집합의 그룹장의 개수를 세어도 된다.


2. 복잡도

접근시간공간
BFS$O(N + E)$$O(N + E)$
DFS$O(N + E)$$O(N + E)$
유니온 파인드$O(N + E)$$O(N)$

($N$ = 입력값 n, $E$ = 입력값 m)


3. 코드

풀이 1: BFS [Java][C++]

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
import java.io.*;
import java.util.*;

public class Main {

    static List<Integer>[] adj;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        adj = new ArrayList[1 + n];
        for (int i = 1; i <= n; i++) {
            adj[i] = new ArrayList<>();
        }

        while (m-- > 0) {
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            adj[u].add(v);
            adj[v].add(u);
        }

        boolean[] vis = new boolean[1 + n];
        int cnt = 0;
        for (int node = 1; node <= n; node++) {
            if (vis[node]) continue;

            bfs(node, vis);
            cnt++;
        }

        System.out.println(cnt);
    }

    static void bfs(int start, boolean[] vis) {
        Queue<Integer> q = new ArrayDeque<>();
        q.offer(start);

        vis[start] = true;

        while (!q.isEmpty()) {
            int cur = q.poll();

            for (int nxt : adj[cur]) {
                if (vis[nxt]) continue;

                q.offer(nxt);
                vis[nxt] = true;
            }
        }
    }
}
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
#include <bits/stdc++.h>
using namespace std;

const int MAX_N = 1 + 1000;
vector<int> adj[MAX_N];
bool vis[MAX_N];

void bfs(int start) {
    queue<int> q;
    q.push(start);

    vis[start] = true;

    while (!q.empty()) {
        int cur = q.front();
        q.pop();

        for (int nxt : adj[cur]) {
            if (vis[nxt]) continue;

            q.push(nxt);
            vis[nxt] = true;
        }
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;

    while (m--) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    int cnt = 0;
    for (int node = 1; node <= n; node++) {
        if (vis[node]) continue;

        bfs(node);
        cnt++;
    }

    cout << cnt;
}

풀이 2: DFS [Java][C++]

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
import java.io.*;
import java.util.*;

public class Main {

    static List<Integer>[] adj;
    static boolean[] vis;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        adj = new ArrayList[1 + n];
        for (int i = 1; i <= n; i++) {
            adj[i] = new ArrayList<>();
        }

        while (m-- > 0) {
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            adj[u].add(v);
            adj[v].add(u);
        }

        vis = new boolean[1 + n];
        int cnt = 0;
        for (int node = 1; node <= n; node++) {
            if (vis[node]) continue;

            dfs(node);
            cnt++;
        }

        System.out.println(cnt);
    }

    static void dfs(int cur) {
        vis[cur] = true;

        for (int nxt : adj[cur]) {
            if (vis[nxt]) continue;
            dfs(nxt);
        }
    }
}
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
#include <bits/stdc++.h>
using namespace std;

const int MAX_N = 1 + 1000;
vector<int> adj[MAX_N];
bool vis[MAX_N];

void dfs(int cur) {
    vis[cur] = true;

    for (int nxt : adj[cur]) {
        if (vis[nxt]) continue;
        dfs(nxt);
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;

    while (m--) {
        int u, v;
        cin >> u >> v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    int cnt = 0;
    for (int node = 1; node <= n; node++) {
        if (vis[node]) continue;

        dfs(node);
        cnt++;
    }

    cout << cnt;
}

풀이 3: 유니온 파인드 [Java][C++]

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
import java.io.*;
import java.util.*;

public class Main {

    static int[] p;

    static void make(int n) {
        p = new int[1 + n];
        for (int i = 1; i <= n; i++) {
            p[i] = i;
        }
    }

    static int find(int x) {
        if (p[x] == x) return x;
        return p[x] = find(p[x]);
    }

    static void union(int x, int y) {
        p[find(y)] = find(x);
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());
        make(n);

        while (m-- > 0) {
            st = new StringTokenizer(br.readLine());
            int u = Integer.parseInt(st.nextToken());
            int v = Integer.parseInt(st.nextToken());
            union(u, v);
        }

        int cnt = 0;
        for (int node = 1; node <= n; node++) {
            if (node == find(node)) cnt++;
        }

        System.out.println(cnt);
    }
}
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
#include <bits/stdc++.h>
using namespace std;

vector<int> p(1 + 1000, -1);

int find(int x) {
    if (p[x] < 0) return x;
    return p[x] = find(p[x]);
}

void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x != y) p[y] = x;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n, m;
    cin >> n >> m;

    while (m--) {
        int u, v;
        cin >> u >> v;
        unite(u, v);
    }

    int cnt = 0;
    for (int node = 1; node <= n; node++) {
        if (node == find(node)) cnt++;
    }

    cout << cnt;
}

This post is licensed under CC BY 4.0 by the author.