-
문제
접근법
코드
import collectionsdef bfs(v):q = collections.deque() # 앞,뒤로 삽입 삭제가 가능한 dequevisited = [False]*(n+1) # visited 를 false로 초기화q.append(v) # v를 deque에 삽입visited[v] = True # v를 True로 전환level = 0while q:level += 1 # 큐의 길이만큼 whilefor _ in range(len(q)):v = q.popleft() # 큐를 맨 앞에서 제거하고, v를 담는다.if v == end: # 나간 v가 end랑 같으면return level - 1 # level을 -1하고 출력for j in relation[v]: # v와 인접한 사람 중if not(visited[j]): # 방문이 없으면visited[j] = Trueq.append(j) # 큐에 담는다return -1n = int(input())start, end = map(int, input().split())m = int(input())relation = [[] for _ in range(n+1)]for _ in range(m):a, b = map(int, input().split())relation[a].append(b)relation[b].append(a)print(bfs(start))'PS > 백준' 카테고리의 다른 글
[백준_7576] 토마토 by python ( BFS ) (2) 2021.01.17 [백준_1012] 유기농배추 by python ( DFS ) (0) 2021.01.16 [백준_2606] 바이러스 by python ( DFS ) (0) 2021.01.16 [백준_1110] 더하기 사이클 ( 구현 [Implementation] ) (0) 2021.01.16 [백준_1783] 병든나이트 (구현, 그리디) (0) 2021.01.16