题解 | #【模板】单源最短路1#

【模板】单源最短路1

https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8

from collections import defaultdict, deque


def bfs(graph, start, end):
    queue = deque([(start, 0)])
    visited = {start: 0}

    while queue:
        node, dist = queue.popleft()
        if node == end:
            return dist

        for neighbor in graph[node]:
            if neighbor not in visited:
                visited[neighbor] = dist + 1
                queue.append((neighbor, dist + 1))

    return -1  # 如果找不到终点,返回-1


def build_graph(n, m):
    graph = defaultdict(list)
    for _ in range(m):
        u, v = map(int, input().split())
        graph[u].append(v)
        graph[v].append(u)  # 无向图,双向添加边
    return graph


# 输入数据
n, m = map(int, input().split())
graph = build_graph(n, m)

shortest_distance = bfs(graph, 1, n)
print(shortest_distance)

全部评论

相关推荐

10-24 13:36
门头沟学院 Java
Zzzzoooo:更新:今天下午有hr联系我去不去客户端,拒了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务