시작하기무료로 시작하기

Shortest Path III

이 연습 문제 세트의 마지막 문제예요! 이제 두 노드 사이에 경로가 없을 때 False를 반환하는 코드를 작성해 문제를 완성해 주세요.

이 연습은 강의의 일부입니다

Python으로 시작하는 네트워크 분석

강의 보기

연습 안내

  • 큐가 비었는지 확인하세요. [-1]로 큐의 마지막 요소를 확인하면 돼요.
  • 두 노드 사이에 경로가 있는지 여부를 나타내는 적절한 return문을 넣으세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

def path_exists(G, node1, node2):
    """
    This function checks whether a path exists between two nodes (node1, node2) in graph G.
    """
    visited_nodes = set()
    queue = [node1]

    for node in queue:
        neighbors = list(G.neighbors(node))
        if node2 in neighbors:
            print('Path exists between nodes {0} and {1}'.format(node1, node2))
            return True
            break

        else:
            visited_nodes.add(node)
            queue.extend([n for n in neighbors if n not in visited_nodes])

        # Check to see if the final element of the queue has been reached
        if node == ____:
            print('Path does not exist between nodes {0} and {1}'.format(node1, node2))

            # Place the appropriate return statement
            return ____
코드 편집 및 실행