728x90
level 3 : 네트워크
https://programmers.co.kr/learn/courses/30/lessons/43162
코딩테스트 연습 - 네트워크
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있
programmers.co.kr
코드
//프로그래머스 네트워크
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<vector<int>> computers_copy;
bool visited[201] = { false, };
void DFS(int node) {
visited[node] = true; //방문한 노드
for (int i = 0; i < computers_copy.size(); i++) {
if (visited[i] == false) {
if (computers_copy[node][i] == 1) {
DFS(i);
}
}
}
}
int solution(int n, vector<vector<int>> computers) {
int answer = 0;
computers_copy = computers; //전역변수
for (int i = 0; i < n; i++) {
if (visited[i] == false) {
DFS(i);
answer++;
}
}
return answer;
}
int main() {
int n = 3;
vector<vector<int>> computers = { {1,1,0}, {1,1,1}, {0,1,1} };
cout << solution(n, computers) << "\n";
return 0;
}
설명
computers를 computers_copy로 전역 변수 선언하였다. DFS에서 참조형 변수(&)로 선언할 수 있지만 전역변수로 선언하여 더 편하게 구현할 수 있다. 노드의 방문을 확인하는 visited도 마찬가지로 전역변수로 선언해주었다.
방문되지 않은 노드 중 이동할 수 있는 노드인지를 판단하여 이동하게 된다.(DFS)
고찰
백준에서도 DFS/BFS 문제를 많이 풀어봐서 쉽게 구현할 수 있었던거 같다.
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
알고리즘(C++) / 프로그래머스 level 2 : 후보키 (0) | 2021.08.05 |
---|---|
알고리즘(C++) / 프로그래머스 level 2 : 파일명 정렬 (0) | 2021.08.04 |
알고리즘(C++) / 프로그래머스 level 3 : 단어 변환 (0) | 2021.08.01 |
알고리즘(C++) / 프로그래머스 level 2 : 123 나라의 숫자 (0) | 2021.07.28 |
알고리즘(C++) / 프로그래머스 level 2 : 짝지어 제거하기 (0) | 2021.07.26 |
댓글