본문 바로가기
Algorithm/BFS, DFS

[백준] 2644번 촌수계산

by 등촌동 꼬북이 2020. 9. 8.

전에 풀었던 BFS 문제에 미로찾기 코드를 조금 섞어서 풀었다

 

from collections import deque

N = int(input())
start, end = map(int, input().split())
M = int(input())
graph = [set([]) for i in range(N + 1)]

def bfs(graph, start, end):
    visited = []
    que = deque([start])
    qc = deque([0])
    counter = 0
    while que:
        node = que.popleft()
        c = qc.popleft()
        if node in visited:
            continue
        if node == end:
            counter = c
            break
        if node not in visited:
            visited.append(node)
            que.extend(sorted(graph[node]))
            for _ in range(len(graph[node])):
                qc.append(c + 1)

    if counter == 0:
        counter = -1

    return counter


for i in range(M):
    V1, V2 = map(int, input().split())
    graph[V1].add(V2)
    graph[V2].add(V1)

print(bfs(graph, start, end))

'Algorithm > BFS, DFS' 카테고리의 다른 글

[ 백준] 2606번 바이러스  (0) 2020.09.09
[백준] 1012번 유기농 배추  (0) 2020.09.09
[백준] 1926번 그림  (0) 2020.09.07
[백준] 10809번 알파벳 찾기  (0) 2020.09.04
[백준] 단어 공부  (0) 2020.09.04

댓글