mirror of
				https://gitee.com/coder-xiaomo/leetcode-problemset
				synced 2025-11-04 03:33:12 +08:00 
			
		
		
		
	
		
			
				
	
	
		
			45 lines
		
	
	
		
			2.8 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
			
		
		
	
	
			45 lines
		
	
	
		
			2.8 KiB
		
	
	
	
		
			HTML
		
	
	
	
	
	
<p>给你一个有 <code>n</code> 个节点的 <strong>有向带权</strong> 图,节点编号为 <code>0</code> 到 <code>n - 1</code> 。图中的初始边用数组 <code>edges</code> 表示,其中 <code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code> 表示从 <code>from<sub>i</sub></code> 到 <code>to<sub>i</sub></code> 有一条代价为 <code>edgeCost<sub>i</sub></code> 的边。</p>
 | 
						||
 | 
						||
<p>请你实现一个 <code>Graph</code> 类:</p>
 | 
						||
 | 
						||
<ul>
 | 
						||
	<li><code>Graph(int n, int[][] edges)</code> 初始化图有 <code>n</code> 个节点,并输入初始边。</li>
 | 
						||
	<li><code>addEdge(int[] edge)</code> 向边集中添加一条边,其中<strong> </strong><code>edge = [from, to, edgeCost]</code> 。数据保证添加这条边之前对应的两个节点之间没有有向边。</li>
 | 
						||
	<li><code>int shortestPath(int node1, int node2)</code> 返回从节点 <code>node1</code> 到 <code>node2</code> 的路径<strong> 最小</strong> 代价。如果路径不存在,返回 <code>-1</code> 。一条路径的代价是路径中所有边代价之和。</li>
 | 
						||
</ul>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>示例 1:</strong></p>
 | 
						||
 | 
						||
<p><img alt="" src="https://assets.leetcode.com/uploads/2023/01/11/graph3drawio-2.png" style="width: 621px; height: 191px;"></p>
 | 
						||
 | 
						||
<pre><strong>输入:</strong>
 | 
						||
["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]]
 | 
						||
<b>输出:</b>
 | 
						||
[null, 6, -1, null, 6]
 | 
						||
 | 
						||
<strong>解释:</strong>
 | 
						||
Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]);
 | 
						||
g.shortestPath(3, 2); // 返回 6 。从 3 到 2 的最短路径如第一幅图所示:3 -> 0 -> 1 -> 2 ,总代价为 3 + 2 + 1 = 6 。
 | 
						||
g.shortestPath(0, 3); // 返回 -1 。没有从 0 到 3 的路径。
 | 
						||
g.addEdge([1, 3, 4]); // 添加一条节点 1 到节点 3 的边,得到第二幅图。
 | 
						||
g.shortestPath(0, 3); // 返回 6 。从 0 到 3 的最短路径为 0 -> 1 -> 3 ,总代价为 2 + 4 = 6 。
 | 
						||
</pre>
 | 
						||
 | 
						||
<p> </p>
 | 
						||
 | 
						||
<p><strong>提示:</strong></p>
 | 
						||
 | 
						||
<ul>
 | 
						||
	<li><code>1 <= n <= 100</code></li>
 | 
						||
	<li><code>0 <= edges.length <= n * (n - 1)</code></li>
 | 
						||
	<li><code>edges[i].length == edge.length == 3</code></li>
 | 
						||
	<li><code>0 <= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 <= n - 1</code></li>
 | 
						||
	<li><code>1 <= edgeCost<sub>i</sub>, edgeCost <= 10<sup>6</sup></code></li>
 | 
						||
	<li>图中任何时候都不会有重边和自环。</li>
 | 
						||
	<li>调用 <code>addEdge</code> 至多 <code>100</code> 次。</li>
 | 
						||
	<li>调用 <code>shortestPath</code> 至多 <code>100</code> 次。</li>
 | 
						||
</ul>
 |