https://www.acmicpc.net/problem/2606
BFS
from collections import deque
import sys
N = int(sys.stdin.readline().rstrip())
E = int(sys.stdin.readline().rstrip())
graph = [[] for i in range(N+1)]
visited = [False] * (N+1)
for _ in range(E):
a, b = map(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
for i in graph:
i.sort()
def bfs(visited, graph, start):
queue = deque([start])
visited[start] = True
while queue:
v = queue.popleft()
for i in graph[v]:
if not visited[i]:
queue.append(i)
visited[i] = True
bfs(visited, graph, 1)
print(visited.count(True) - 1)
DFS
from collections import deque
import sys
N = int(sys.stdin.readline().rstrip())
E = int(sys.stdin.readline().rstrip())
graph = [[] for i in range(N+1)]
visited = [False] * (N+1)
for _ in range(E):
a, b = map(int, sys.stdin.readline().split())
graph[a].append(b)
graph[b].append(a)
for i in graph:
i.sort()
def dfs(graph, visited, v):
visited[v] = True
for i in graph[v]:
if not visited[i]:
dfs(graph, visited, i)
dfs(graph, visited, 1)
print(visited.count(True) - 1)
- DFS BFS 기본 구현
'CT' 카테고리의 다른 글
[알고리즘 고득점 Kit] Heap : 더 맵게 (0) | 2024.10.05 |
---|---|
[Python] 백준 2667번 : 단지번호붙이기 (0) | 2024.09.09 |
[Python] 백준 2178번 : 미로 탐색 (0) | 2024.09.08 |
[Python] 백준 1260번 : DFS와 BFS (3) | 2024.07.24 |
[Python] 백준 2346번 : 풍선 터뜨리기 (0) | 2024.07.23 |
댓글