Agorithm/백준 알고리즘
백준 알고리즘 14496번 그대, 그머가 되어(python)
kimjinho1
2021. 3. 16. 14:12
728x90
반응형
단순한 BFS 문제이다. 근데 a == b일 때를 생각 못하고 처리를 안 해서 엄청나게 많이 틀렸다. 주의하도록 하자
from collections import deque
def bfs(a, b):
q = deque()
q.append(a)
check[a] = 0
while q:
node = q.popleft()
if node == b:
return check[node]
for n in graph[node]:
if check[n] == -1:
q.append(n)
check[n] = check[node]+1
return -1
a, b = map(int, input().split())
N, M = map(int, input().split())
graph = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, input().split())
if u == v:
continue
graph[u].append(v)
graph[v].append(u)
check = [-1]*(N+1)
print(bfs(a, b))
728x90
반응형