boj-11724 연결 요소의 개수

10340 단어 BFSDFSBFS

DFS

def dfs(s, d, visited):
    visited[s] = True
    for v in d[s]:
        if not visited[v]:
            dfs(v, d, visited)

n,m = map(int, input().split())
d = [ [] for _ in range(n+1)]
for _ in range(m):
    a,b = map(int, input().split())
    d[a].append(b)
    d[b].append(a)

result = 0
visited = [False] * (n+1)
for i in range(1, n+1):
    if visited[i] == 0:
        result += 1
        dfs(i,d, visited)
print(result)

BFS

from collections import deque
def bfs(s,d,visited):
    queue = deque([s])
    visited[s] = True
    while queue:
        v = queue.popleft()
        for i in d[v]:
            if not visited[i] :
                queue.append(i)
                visited[i] = True

n,m = map(int, input().split())
d = [ [] for _ in range(n+1)]
for _ in range(m):
    a,b = map(int, input().split())
    d[a].append(b)
    d[b].append(a)

result = 0
visited = [False] * (n+1)
for i in range(1, n+1):
    if visited[i] == 0:
        result += 1
        bfs(i,d, visited)
print(result)

좋은 웹페이지 즐겨찾기