👩💻 알고리즘 풀이/프로그래머스
[프로그래머스/C++] 네트워크 풀이
choidam
2020. 9. 29. 17:03
프로그래머스 : 네트워크
문제 링크 : programmers.co.kr/learn/courses/30/lessons/43162
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있��
programmers.co.kr
문제
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
#include <string>
#include <vector>
using namespace std;
vector<vector<int>> map;
vector<bool> visited;
int ans, num;
void dfs(int node){
visited[node] = true; // 방문 표시
// 탐색
for(int i=0; i<num; i++){
if(map[node][i]==1 && visited[i]==false){
dfs(i);
}
}
}
int solution(int n, vector<vector<int>> computers) {
// 전역변수 초기화
map = computers; ans = 0; num = n;
for(int i=0; i<n; i++){
visited.push_back(false);
}
for(int i=0; i<n; i++){
if(visited[i]==false){
ans++;
dfs(i);
}
}
return ans;
}
정말 간단한 DFS문제이다!
근데 문득 나만 이런 방법으로 전역변수를 초기화 하나 싶어서 궁금해서 다른 사람의 풀이를 찾아봤다.
#include <string>
#include <vector>
using namespace std;
void DFS(int point, vector<vector<int>>& computers, vector<bool>& visit, int n){
visit[point] = true;
for (int i = 0; i < n; i++) {
if (!visit[i] && computers[point][i]) DFS(i, computers, visit, n);
}
}
int solution(int n, vector<vector<int>> computers) {
int answer = 0;
vector<bool> visit(n, false);
for (int i = 0; i < n; i++) {
if (!visit[i]) {
answer++;
DFS(i, computers, visit, n);
}
}
return answer;
}
출처 : Kimn's Blog
훨씬 간결하다. 전역변수를 초기화 하는 방법 대신 포인터를 사용해 구현했다. 이런 방법이..❗️
포인터 귀찮아서 하나도 사용 안 하는데 ㅠㅠ 사용하는 버릇을 들여야 겠다.