728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43162?language=cpp
(1) C++
#include <string>
#include <vector>
#define MAX 201
using namespace std;
int visited[MAX] = {0,};
void dfs(int current, int n, vector<vector<int>> graph){
visited[current] = 1;
for(int i = 0; i < n; i++){
if(visited[i] == 0 && graph[current][i] == 1){
dfs(i, n, graph);
}
}
}
int solution(int n, vector<vector<int>> computers) {
int answer = 0;
for(int i = 0; i < n; i++){
if (visited[i] == 0){
dfs(i, n, computers);
answer ++;
}
}
return answer;
}
(2) Python
from collections import deque
def solution(N, computers):
answer = 0
visited = [0] * N
for i in range(N):
if visited[i] == 1:
continue
else:
q = deque()
q.append(i)
while q:
v = q.popleft()
for j in range(N):
if visited[j] == 0 and computers[v][j] == 1:
visited[j] = 1
q.append(j)
answer += 1
return answer
728x90
'Study > Coding Test' 카테고리의 다른 글
[프로그래머스] K번째수 Python, C++ (0) | 2023.08.01 |
---|---|
[프로그래머스] 게임 맵 최단거리 Python, C++ (0) | 2023.07.31 |
[백준] 15486 - 퇴사 2 Python (0) | 2023.07.07 |
[백준] 2295 - 세 수의 합 Python (0) | 2023.07.04 |
[백준] 14940 - 쉬운 최단거리 Python (0) | 2023.07.04 |