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

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (๋„คํŠธ์›Œํฌ, ๊นŠ์ด/๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰(DFS/BFS)) C++

by UKHYUN22 2021. 12. 30.
728x90

 

์ดˆ๋ฐ˜์— ๋ฌธ์ œ Setting ํ•  ๋•Œ ์‹œ๊ฐ„์ด ๋งŽ์ด ๊ฑธ๋ ธ๊ณ  ๋ฌถ์ธ ๊ฒƒ์ด ๋ช‡ ๊ฐœ์ธ์ง€ ํŒŒ์•…ํ•˜๋Š” ๊ฒƒ์—์„œ๋„ ๋งŽ์ด ์‹œ๊ฐ„์„ ์ผ๋‹ค. ํ•˜๋‹ค๋ณด๋‹ˆ๊นŒ visited ํ•˜์ง€ ์•Š์€ ๊ฒƒ์„ ์‹œ์ž‘ํ•  ๋•Œ๊ฐ€ ๋„คํŠธ์›Œํฌ๊ฐ€ ๋‹ฌ๋ผ์ง€๋Š” ์ˆœ๊ฐ„์ด์—ˆ๋‹ค. 

 

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

using namespace std;

int solution(int n, vector<vector<int>> computers) {
    int answer = 0;
    vector<vector<int>> adj(n+1);
    vector<int> visited(n+1, 0);
    queue<int> queue;
    
    // Diagonal Matrix ์ด๋ฏ€๋กœ Upper์— ํ•ด๋‹นํ•˜๋Š” ๊ฒƒ๋งŒ ์ทจํ•ด์„œ adjacent list ๋งŒ๋“ค๊ธฐ
    for(int i = 0 ; i < n ; i++) {
        for(int j = i+1 ; j < n ; j++) {
            if(computers[i][j] == 1) {
                adj[i+1].push_back(j+1);
                adj[j+1].push_back(i+1);
            }
        }
    }
    
    // BFS๋ฅผ ์ด์šฉํ•ด์„œ visited ํ•˜์ง€ ์•Š์€ ์‚ฌ์ดํด์„ ๋Œ ๋•Œ๋งˆ๋‹ค answer ๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
    for(int i =1 ; i <= n ; i++) {
        if(visited[i] == 1) continue;
        queue.push(i);
        visited[i] = 1;
        
        while(!queue.empty()) {
            int node = queue.front();
            queue.pop();
            
            for(int j = 0 ; j < adj[node].size() ; j++) {
                if(!visited[adj[node][j]]) {
                    visited[adj[node][j]] = 1;
                    queue.push(adj[node][j]);
                }
            }
        }
        answer++;
    }
    
    return answer;
}