알고리즘/프로그래머스

Programers 네트워크

내이름은 킹햄찌 2022. 3. 12. 21:28

https://programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

#include <string>
#include <vector>
#include <queue>
using namespace std;
vector<int> adj[201];
bool visited[2001];
int sol;

void bfs(int cur){
    if(visited[cur]) return;
    visited[cur] = true;
    
    queue<int> q;
    q.push(cur);
    
    while(!q.empty()){
        int current = q.front();
        q.pop();
        for(int i =0; i<adj[current].size();i++){
            int next = adj[current][i];
            if(visited[next]) continue;
            q.push(next);
            visited[next] = true;
        }
        if (q.size() == 0) sol++;
    }
}

int solution(int n, vector<vector<int>> computers) {
    int answer = 0;
    fill(visited,visited+n,false);
    for(int i=0;i<n;i++){
        for(int j =0;j<n;j++){
            if(i == j) continue;
            if(computers[i][j])
                adj[i].push_back(j);
        }
    }
    for(int i =0;i<n;i++)
        bfs(i);
    answer = sol;
    return answer;
}

아이디어

노선을 원하는 포멧으로 파싱하여 BFS 사용

BFS보다는 DFS를 사용하는 것이 더 적합한 문제이지만 계속 DFS만 쓰니 지루해서 BFS 사용