Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chapter 09, 미래 도시 다른 풀이 #180

Open
yuna1212 opened this issue Apr 8, 2022 · 0 comments
Open

Chapter 09, 미래 도시 다른 풀이 #180

yuna1212 opened this issue Apr 8, 2022 · 0 comments

Comments

@yuna1212
Copy link

yuna1212 commented Apr 8, 2022

간선 가중치가 1이기 때문에 BFS로 더 빠르게 풀이할 수 있을 것 같습니다.
이 경우 큐에 넣고 빼기 위한 연산이 최대 간선의 개수만큼 반복되므로 시간 복잡도는 O(E)=O(V^2)입니다.
이 풀이도 적절한가요??

from collections import deque
 
def get_distance(graph, start, destination):
    """ BFS로 최단 거리 구하기 """
    queue = deque([(start, 0)])
    visited = set()
    while queue:
        here, distance = queue.popleft()
        if here == destination:
            return distance
        if here not in visited:
            visited.add(here)
            for next in graph[here]:
                queue.append((next, distance + 1))
    return -1
 
# 입력
n, m = map(int, input().split())
graph = [[] for _ in range(n+1)]
for _ in range(m):
    node1, node2 = map(int, input().split())
    graph[node1].append(node2)
    graph[node2].append(node1)
x, k = map(int, input().split())
 
# 출력
meetting_distance = get_distance(graph, 1, k)
if meetting_distance > -1:
    dating_distance = get_distance(graph, 1, x)
    if dating_distance > -1:
        print(meetting_distance + dating_distance)
    else:
        print(-1)
else:
    print(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant