촌수계산 BFS

Seomingi·2023년 1월 30일
0

BFS/DFS

목록 보기
4/5
#촌수계산
from collections import deque
def bfs(s):
    queue = deque([s])
    visit[s] = True
    
    while queue:
        x = queue.popleft()
        for i in graph[x]:
            if not visit[i]:
                queue.append(i)
                check[i] = check[x] + 1
                visit[i] = True
    
    
    
n = int(input())
m1,m2 = map(int,input().split())
k = int(input())

graph = [[] for i in range(n+1)]
for i in range(k):
    s,e = map(int,input().split())
    graph[s].append(e)
    graph[e].append(s)
#print(graph)
visit = [False] * (n+1)
check = [0] * (n+1)

bfs(m1)
#print(check)
if check[m2] > 0:
    print(check[m2])
else:
    print(-1)
profile
One thing after another

0개의 댓글

관련 채용 정보