[프로그래머스] 네트워크

rhkr9080·2023년 12월 23일
0

프로그래머스

목록 보기
14/19

문제링크 : https://school.programmers.co.kr/learn/courses/30/lessons/43162

💻 문제 풀이 : Python

⭐ DFS
def Dfs(n, computers, com, visited):
    visited[com] = True
    # com번째 컴퓨터 조회
    for i in range(n):
        if(i != com and computers[com][i] == 1 and visited[i] == False):
            Dfs(n, computers, i, visited)
        

def solution(n, computers):
    visited = [False for _ in range(n)] # 방문 기록
    answer = 0
    
    for com in range(n):
        # 아직 방문하지 않았으면,
        if (visited[com] == False):
            Dfs(n, computers, com, visited)
            answer += 1
    return answer

⭐ BFS

from collections import deque

def Bfs(n, computers, com, visited):
    Q = deque()
    Q.append(com)
    
    while(len(Q) > 0):
        com = Q.pop()
        visited[com] = True
        
        for i in range(n):
            if (visited[i] == False and
               computers[i][com] == 1 and i != com):
                Q.append(i)

def solution(n, computers):
    answer = 0
    visited = [False for _ in range(n)]

    for com in range(n):
        if visited[com] == False:
            Bfs(n, computers,com,visited)
            answer += 1
    
    return answer

출처 : https://velog.io/@soorim_yoon/DFSBFS-네트워크-프로그래머스-Level-3


📌 memo

profile
공부방

0개의 댓글