노트

[백준] 2644번 촌수계산 python 본문

알고리즘

[백준] 2644번 촌수계산 python

_Myway 2023. 7. 1. 21:19
n = int(input())
a,b = map(int,input().split())
m = int(input())

relation = [[0]*101 for _ in range(101)]
visited = [0]*101
q = []

for i in range(m):
    x,y = map(int,input().split())
    relation[x][y]=relation[y][x]=1

def dfs():
    visited[a]=1
    q.append(a)

    while q:
        k = q.pop(0)
        if k==b:
            return

        for j in range(1,n+1):
            if relation[k][j]==1 and visited[j]==0:
                visited[j]=visited[k]+1
                q.append(j)

dfs()
if visited[b]==0:
    print(-1)
else:
    print(visited[b]-1)
Comments