Notice
Recent Posts
Recent Comments
Link
나의 개발일지
[백준] 2606번 바이러스, 양방향 그래프 표현 (defaultdict) [Python] 본문
- 백준 문제 : https://www.acmicpc.net/problem/2606
- 기본 딕셔너리는 찾는 키 값이 없으면 오류를 반환하지만 defaultdict는 키 값이 없으면 주어진 기본 값을 반환한다.
- 지금은 list를 기본 값으로 주어서 key : [] 형태의 기본 값을 가지고 있다.
- 그렇기 때문에 키의 존재 여부를 확인하지 않고 append를 할 수 있다.
from collections import defaultdict
n = int(input())
m = int(input())
graph = defaultdict(list) # 딕셔너리 기본 값을 리스트로 선언
for i in range(m): # 양방향 그래프 구현
x, y = map(int, input().split())
graph[x].append(y)
graph[y].append(x)
visit = [0] * (n+1)
visit[1] = 1
def dfs(n):
for i in graph[n]:
if visit[i] == 0:
visit[i] = 1
dfs(i)
dfs(1)
print(visit.count(1) - 1)
'백준' 카테고리의 다른 글
[백준] 7562번 나이트의 이동 [Python] (0) | 2023.07.31 |
---|---|
[백준] 1260번 DFS와 BFS [Python] (0) | 2023.07.31 |
[Python] 정규식 (0) | 2023.06.14 |
[Python] 리스트 함수 시간 복잡도 (0) | 2023.04.05 |
[Python] 소인수 분해 알고리즘 (0) | 2023.03.03 |
Comments