가장 먼 노드 with 파이썬 본문
728x90
from collections import defaultdict, deque
def bfs(graph, start, distances, visited):
q = deque([start])
visited[start] = True
while q:
current = q.popleft()
for adj in graph[current]:
if not visited[adj]:
visited[adj] = True
q.append(adj)
distances[adj] = distances[current] + 1
def solution(n, edge):
# 그래프 만들기
graph = defaultdict(list)
visited = [False] * (n+1)
for x, y in edge:
graph[x].append(y)
graph[y].append(x)
# bfs 탐색 (최단 거리 구하기 위함)
distances = [0]*(n+1)
bfs(graph, 1, distances, visited)
return distances.count(max(distances))
'Algorithms > BFS and DFS' 카테고리의 다른 글
배열 돌리기 4 [17406] with 파이썬 (0) | 2020.06.05 |
---|---|
2048 (Easy) [12100] with 파이썬 (0) | 2020.06.04 |
Mooyo Mooyo [16768] with 파이썬 (0) | 2020.06.04 |
과외맨 [5213] with 파이썬 (0) | 2020.06.02 |
바이러스 [2606] with 파이썬 (0) | 2020.06.02 |
Comments