코딩딩딩

(python) 백준 2606 - 바이러스 (DFS활용) 본문

백준

(python) 백준 2606 - 바이러스 (DFS활용)

komizke 2023. 1. 31. 23:32

백준 2606

https://www.acmicpc.net/problem/2606

 

2606번: 바이러스

첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어

www.acmicpc.net

 

1. 문제 설명

 

문제에서 제시된 <그림 1>처럼 그래프를 구성하여 1번 컴퓨터와 연결된 컴퓨터를 탐색하는 그래프 탐색 문제.

 

2. 문제 풀이

 

그래프를 인접행렬로 구성한다.

 

graph = [[] for _ in range(n+1)]    #인접행렬 그래프

for _ in range(m):
    a, b = map(int, input().split())    
    graph[a].append(b)  #a, b연결
    graph[b].append(a)  #a, b연결

 

1번 정점을 시작으로 DFS알고리즘으로 1번 정점과 연결된 정점들을 모두 방문한다.

 

def dfs(s):
    global cnt
    visited[s] = 1	#정점s에 대해 방문체크
    for i in graph[s]:
        if visited[i] == 0: #미방문여부 확인
            dfs(i)  #방금 방문한 정점에 대하여 dfs수행
            cnt += 1

 

깊이우선탐색(DFS) 참고 링크: https://michelangeloo.tistory.com/5

 

(python) 그래프 순회 - 깊이 우선 탐색(DFS) (Feat. 백준 11403)

1. 깊이 우선 탐색(Depth-First Search) 깊이 우선 탐색 방식은 출발 정점으로부터 시작하여 연결된 정점을 거쳐 가장 멀리 있는 정점까지 방문하며 모든 정점을 방문하는 방식. 탐색하는 과정에서 더

michelangeloo.tistory.com

 

3. 전체 코드

 

def dfs(s):
    global cnt
    visited[s] = 1
    for i in graph[s]:
        if visited[i] == 0: #미방문 확인
            dfs(i)  #방금 방문한 정점에 대하여 dfs수행
            cnt += 1

n = int(input())    #컴퓨터 수
m = int(input())    #번호 쌍 수

graph = [[] for _ in range(n+1)]    #인접행렬 그래프

for _ in range(m):
    a, b = map(int, input().split())
    graph[a].append(b)  #a, b연결
    graph[b].append(a)  #a, b연결
    
visited = [0 for _ in range(n+1)]   #방문여부 체크
cnt = 0
dfs(1)
print(cnt)

'백준' 카테고리의 다른 글

(python) 백준 7576 - 토마토 (bfs 풀이)  (2) 2023.02.04
(python) 백준18870 - 좌표 압축  (1) 2023.02.04
(python) 백준 2292 - 벌집  (0) 2023.01.30
(python) 백준 1912 - 연속합  (0) 2023.01.28
(python) 백준 1759 - 암호 만들기  (1) 2023.01.25
Comments