๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Beakjoon] 11724๋ฒˆ ์—ฐ๊ฒฐ์š”์†Œ

ibelieveinme 2022. 5. 10. 11:14
728x90

[๋ฌธ์ œ]

 

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


[ํ’€์ด]

๋ฒกํ„ฐ๋ฅผ ํ™œ์šฉํ•œ ์ธ์ ‘๋ฆฌ์ŠคํŠธ์™€ DFS๋กœ ํ’ˆ~!

 

*๋™์ ํ• ๋‹น๋ถ€๋ถ„ ๊ธฐ์–ตํ•˜๊น…...

vector<int> *graph = new vector<int>[vertexNum + 1]; //์ธ์ ‘๋ฆฌ์ŠคํŠธ ๋™์ ํ• ๋‹น
bool *visited = new bool[vertexNum + 1];

 

[ํ’€์ด ์ฝ”๋“œ]

#include <iostream>
#include <vector>
using namespace std;

void dfs(int vertex, vector<int> graph[], bool *visited);

int main() {
    int vertexNum, edgeNum, u, v;
    cin >> vertexNum >> edgeNum;

    vector<int> *graph = new vector<int>[vertexNum + 1]; //์ธ์ ‘๋ฆฌ์ŠคํŠธ ๋™์ ํ• ๋‹น
    bool *visited = new bool[vertexNum + 1];

    for (int i = 0; i < edgeNum; i++) {
        cin >> u >> v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    for (int i = 0; i < vertexNum; i++) visited[i] = false;

    int count = 0;
    for (int i = 1; i <= vertexNum; i++) {
        if (!visited[i]) {
            dfs(i, graph, visited);
            count++;
        }
    }
    cout << count;

    delete[] visited;
    return 0;
}

void dfs(int vertex, vector<int> graph[], bool *visited) {
    visited[vertex] = true;
    for (int i = 0; i < graph[vertex].size(); i++) {
        if (!visited[graph[vertex][i]]) dfs(graph[vertex][i], graph, visited);
    }
}
728x90