tech.junha.kr

네트워크 DFS, BFS풀이

문제 설명

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있을 때 컴퓨터 A와 컴퓨터 C도 간접적으로 연결되어 정보를 교환할 수 있습니다. 따라서 컴퓨터 A, B, C는 모두 같은 네트워크 상에 있다고 할 수 있습니다.

컴퓨터의 개수 n, 연결에 대한 정보가 담긴 2차원 배열 computers가 매개변수로 주어질 때, 네트워크의 개수를 return 하도록 solution 함수를 작성하시오.

풀이1 - DFS

def DFS(n, computers, visited, i):
    visited[i] = True

    for j in range(n):
        if computers[i][j] ==1 and visited[j] == False:
            DFS(n, computers, visited, j)

def solution(n, computers):
    answer = 0
    visited = [False] * n
    for i in range(n):
        if visited[i] == False :
            DFS(n, computers, visited, i)
            answer += 1
    return answer

문제의 핵심

  1. DFS를 이진트리로만 봤던 것이 이 문제의 큰 장애물이 됐음.

  2. 네트워크는 연결되어 있고, 그것을 트리로 보고, 깊이 우선 탐색으로 더이상 연결된 노트가 없다면, 그것으로 하나의 네트워크라고 본 것.

풀이2 - BFS

def BFS(n, computers, visited, i):
    stack = [i]

    while stack :
        k = stack.pop()
        if visited[k] == False:
            visited[k] = True
        for j in range(n):
            if visited[j] == False and computers[k][j] == 1 :
                stack.append(j)

def solution(n, computers):
    answer = 0
    visited = [False] * n

    for i in range(n):
        if visited[i] == False:
            BFS(n, computers, visited, i )
            answer +=1

    return answer

풀이3 - BFS

def BFS(n, computers):
    answer = 0
    visited =[False] * n

    for i in range(n):
        if visited[i] == False:
            stack =[i]
            while stack:
                k = stack.pop()
                visited[k] = True
                for j in range(n):
                    if computers[k][j] == 1 and visited[j] == False:
                        stack.append(j)
            answer +=1
    return answer

def solution(n, computers):
    return BFS(n, computers)

print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]))

오류 이유

While stack: 부분에서

visited[k] = True를 조건문없이 썼다.

조건문 없이 쓰니, stack이 쌓인 노드들의

.... 가 아니라

visited[k] == True라고 썼다. ㅡㅡ

내가 찾은 이유는 상황에 끼어맞춘 것이였고,

정확한 이유는 문법 오류에 있다.

그럼 당연히 방문체크가 되지 않고,

While문에서 쌓인 스택에서 방문하지 않았을 때 쌓이는

stack.append(j)가 계속해서 쌓이고 다음 함수로 넘어가지 않아

BFS함수의 리턴값이 none으로 나왔던 거시였다..!