-
[프로그래머스] 네트워크알고리즘/프로그래머스 2021. 5. 21. 17:07
문제 설명
네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.
컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.
제한사항
컴퓨터의 개수 n은 1 이상 200 이하인 자연수입니다.
각 컴퓨터는 0부터 n-1인 정수로 표현합니다.
i번 컴퓨터와 j번 컴퓨터가 연결되어 있으면 computers[i][j]를 1로 표현합니다.
computer[i][i]는 항상 1입니다.입출력 예
n computers return
3 [[1, 1, 0], [1, 1, 0], [0, 0, 1]] 2
3 [[1, 1, 0], [1, 1, 1], [0, 1, 1]] 1풀이
백준에 있는 섬 개수 찾기와 많이 비슷합니다.
DFS
와BFS
로 풀 수 있습니다.DFS
는 깊이 우선 탐색이므로 분기를 만나면 계속 깊게 들어갑니다. 재귀적으로 구현하는 것이 직관적이라고 생각합니다. 깊이가 너무 깊어질 때는 스택 오버플로우가 생기므로stack
자료구조를 사용하거나queue
를 이용해BFS
로 풀어야 합니다.DFS(재귀)
#include <string> #include <vector> using namespace std; void dfs(int n, int origin, vector<vector<int>>& computers, bool (&visited)[200]) { visited[origin] = true; for (int i = 0; i < n; ++i) { if (computers[origin][i] == 1 && visited[i] == false) dfs(n, i, computers, visited); } } int solution(int n, vector<vector<int>> computers) { int answer = 0; bool visited[200] = { false }; for (int i = 0; i < n; ++i) { if (visited[i]) continue; ++answer; dfs(n, i, computers, visited); } return answer; }
BFS
#include <string> #include <vector> queue<int> q; using namespace std; bool visited[200] = { false }; void bfs(int n, int origin, vector<vector<int>>& computers) { visited[origin] = true; q.push(origin); while (!q.empty()) { int ori = q.front(); for (int i = 0; i < n; ++i) { if (computers[ori][i] == 1 && visited[i] == false) { visited[i] = true; q.push(i); } } q.pop(); } } int solution(int n, vector<vector<int>> computers) { int answer = 0; for (int i = 0; i < n; ++i) { if (visited[i]) continue; ++answer; bfs(n, i, computers); } return answer; }
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 기능 개발 (0) 2021.07.06 [프로그래머스] 124의 나라 (0) 2021.07.04 [프로그래머스] 소수 찾기 (0) 2021.05.15 [알고리즘] 피보나치 수열 (0) 2021.04.12 [프로그래머스] 쇠막대기 (0) 2020.02.19