๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ BaekJoon

๋ฐฑ์ค€ BaekJoon (๋ฐ”์ด๋Ÿฌ์Šค, 2606) C++

by UKHYUN22 2022. 1. 5.
728x90

 

BFS ๋กœ ๊ฐ„๋‹จํ•˜๊ฒŒ ์‚ฌ์ดํด์— visitedํ•˜๊ฒŒ ๋˜๋Š” node๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ์„ธ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

 

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main() {
    int computer = 0;
    int num = 0;

    cin >> computer;
    cin >> num;

    vector<vector<int>> adj(computer+1);
    vector<int> visited(computer, 0);
    queue<int> q;

    for(int i = 0 ; i < num ; i++) {
        int one = 0, two = 0;
        cin >> one >> two;

        adj[one].push_back(two);
        adj[two].push_back(one);
    }

    // for(int i =1 ; i < adj.size() ; i++) {
    //     cout << "[ " << i << " ] ";
    //     for(int j =0  ; j < adj[i].size() ; j++) {
    //         cout << adj[i][j] << " ";
    //     }
    //     cout << endl;
    // }

    int connected = 0;

    q.push(1);
    visited[1] = 1;

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

        for(int i = 0 ; i < adj[node].size() ; i++) {
            if(visited[adj[node][i]] == 0) {
                connected++;
                visited[adj[node][i]] = 1;
                q.push(adj[node][i]);
            }
        }
    }

    cout << connected ;

    return 0;
}