#문제
2606번: 바이러스
첫째 줄에는 컴퓨터의 수가 주어진다. 컴퓨터의 수는 100 이하이고 각 컴퓨터에는 1번 부터 차례대로 번호가 매겨진다. 둘째 줄에는 네트워크 상에서 직접 연결되어 있는 컴퓨터 쌍의 수가 주어
www.acmicpc.net
#풀이 & 학습한 내용
"BFS나 DFS로 그래프를 순회해서 방문할 수 있는 정점을 찾는 문제"입니다. supremo7.tistory.com/174에서 구현한 DFS와 BFS코드를 조금만 변형하면 구현 가능했고, 이번 문제는 방문하지 않은 노드가 여러 개일 때, 꼭 번호가 낮은 순서부터 처리할 필요가 없어 아래 코드 35번째 줄 반복문에서 sort를 해주지 않았습니다.
#소스코드
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
from collections import deque
count = 0 #방문된 노드를 count
def dfs(graph,V,visited):
global count
visited[V]=True
count+=1
for i in graph[V]:
if not visited[i]:
dfs(graph,i,visited)
def bfs(graph,start,visited):
global count
queue=deque([start])
visited[start]=True
while queue:
v = queue.popleft()
visited[v]=True
count+=1
for i in graph[v]:
if not visited[i]:
queue.append(i)
visited[i]=True
com = int(input())
net = int(input())
#방문여부 확인하는 리스트 초기화
visited=[False]*(com+1)
#인접리스트 초기화
graph = [[] for _ in range(com+1)]
for i in range(net):
c1,c2=map(int,input().split())
graph[c1].append(c2)
graph[c2].append(c1)
#dfs(graph,1,visited)
bfs(graph,1,visited)
print(count-1) #1번 컴퓨터는 제외
|
cs |
github.com/HoYoungChun/Algorithm_PS/blob/master/DFS%26BFS/BOJ_2606.py
HoYoungChun/Algorithm_PS
Baekjoon Online Judge, Programmers problem solving by Python, C++ - HoYoungChun/Algorithm_PS
github.com
'Algorithm > DFS&BFS' 카테고리의 다른 글
| [Python] 백준 7576번 : 토마토 (S1) - DFS&BFS단계별6 (0) | 2021.03.03 |
|---|---|
| [Python] 백준 2178번 : 미로 탐색 (S1) - DFS&BFS단계별5 (0) | 2021.02.03 |
| [Python] 백준 1012번 : 유기농 배추 (S2) - DFS&BFS단계별4 (0) | 2021.02.01 |
| [Python] 백준 2667번 : 단지번호붙이기 (S1) - DFS&BFS단계별3 (0) | 2021.02.01 |
| [Python] 백준 1260번 : DFS와 BFS (S2) - DFS&BFS단계별1 (0) | 2021.01.28 |