LeetCode 2642 设计可以求最短路径的图类

文章描述了一道LeetCode题目,要求实现一个有向带权图类,包括构造图、添加边以及查找两个节点间最短路径的功能。使用邻接表存储图结构,并通过优先队列求解最短路径。示例展示了图的构建、路径查找及边的添加过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 2642 设计可以求最短路径的图类

题目链接

给你一个有 n 个节点的 有向带权 图,节点编号为 0 到 n - 1 。图中的初始边用数组 edges 表示,其中 edges[i] = [fromi, toi, edgeCosti] 表示从 fromi 到 toi 有一条代价为 edgeCosti 的边。
请你实现一个 Graph 类:

  • Graph(int n, int[][] edges) 初始化图有 n 个节点,并输入初始边。
  • addEdge(int[] edge) 向边集中添加一条边,其中 edge = [from, to, edgeCost] 。数据保证添加这条边之前对应的两个节点之间没有有向边。
  • int shortestPath(int node1, int node2) 返回从节点 node1 到 node2 的路径 最小 代价。如果路径不存在,返回 -1 。一条路径的代价是路径中所有边代价之和。
    示例 1:

在这里插入图片描述

输入:
["Graph", "shortestPath", "shortestPath", "addEdge", "shortestPath"]
[[4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]], [3, 2], [0, 3], [[1, 3, 4]], [0, 3]]
输出:
[null, 6, -1, null, 6]

解释:
Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);
g.shortestPath(3, 2); // 返回 6 。从 32 的最短路径如第一幅图所示:3 -> 0 -> 1 -> 2 ,总代价为 3 + 2 + 1 = 6 。
g.shortestPath(0, 3); // 返回 -1 。没有从 03 的路径。
g.addEdge([1, 3, 4]); // 添加一条节点 1 到节点 3 的边,得到第二幅图。
g.shortestPath(0, 3); // 返回 6 。从 03 的最短路径为 0 -> 1 -> 3 ,总代价为 2 + 4 = 6
class Graph:
    def __init__(self, n: int, edges: List[List[int]]):
        self.n = n
        self.graph = [[] for _ in range(n)]  # 邻接表
        for u, v, c in edges:
            self.graph[u].append((v, c))

    def addEdge(self, edge: List[int]) -> None:
        u, v, c = edge
        self.graph[u].append((v, c))

    def shortestPath(self, node1: int, node2: int) -> int:
        dist = [-1] * self.n  # 最短距离数组,初始为-1
        dist[node1] = 0
        visited = [False] * self.n  # 记录节点是否被访问过
        pq = [(0, node1)]  # 小根堆,记录最短距离和节点编号
        while pq:
            cur_dist, cur_node = heapq.heappop(pq)
            if visited[cur_node]:  # 跳过已经访问过的节点
                continue
            visited[cur_node] = True
            if cur_node == node2:  # 找到终点,直接返回
                return dist[node2]
            for next_node, next_dist in self.graph[cur_node]:
                if visited[next_node]:  # 跳过已经访问过的节点
                    continue
                if dist[next_node] == -1 or cur_dist + next_dist < dist[next_node]:
                    dist[next_node] = cur_dist + next_dist
                    heapq.heappush(pq, (dist[next_node], next_node))
        return -1  # 没有找到路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旺 崽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值