Created
July 30, 2025 09:08
-
-
Save inspirit941/5bd504026c85a61129bdba47cb5f0401 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import deque, defaultdict | |
| def bfs(nodes, start, end, visited, tables): | |
| visited.add(start) | |
| queue = deque([(start, 0)]) | |
| while queue: | |
| node, cnt = queue.popleft() | |
| if node in end: | |
| tables[node] = cnt | |
| for _next in nodes[node]: | |
| if _next not in visited and _next in end: | |
| tables[_next] = cnt + 1 | |
| if _next not in visited: | |
| visited.add(_next) | |
| queue.append((_next, cnt+1)) | |
| return | |
| def solution(n, roads, sources, destination): | |
| # 목적지 기준으로, 출발지까지의 거리를 역산하면 bfs로 한 번에 계산할 수 있어보인다. | |
| nodes = defaultdict(set) | |
| for a, b in roads: | |
| nodes[a].add(b) | |
| nodes[b].add(a) | |
| visited = set() | |
| answer_table = defaultdict(lambda: -1) | |
| source_set = set(sources) | |
| bfs(nodes, destination, sources, visited, answer_table) | |
| answer = [answer_table[a] for a in sources] | |
| return answer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment