<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dijkstra Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/dijkstra/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/dijkstra/</link>
	<description></description>
	<lastBuildDate>Mon, 01 May 2023 04:41:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>dijkstra Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/dijkstra/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2662. Minimum Cost of a Path With Special Roads</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2662-minimum-cost-of-a-path-with-special-roads/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2662-minimum-cost-of-a-path-with-special-roads/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 18:03:03 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[dijkstra]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10044</guid>

					<description><![CDATA[<p>You are given an array&#160;start&#160;where&#160;start = [startX, startY]&#160;represents your initial position&#160;(startX, startY)&#160;in a 2D space. You are also given the array&#160;target&#160;where&#160;target = [targetX, targetY]&#160;represents your&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2662-minimum-cost-of-a-path-with-special-roads/">花花酱 LeetCode 2662. Minimum Cost of a Path With Special Roads</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2662. Minimum Cost of a Path With Special Roads - 刷题找工作 EP411" width="500" height="281" src="https://www.youtube.com/embed/oBtS4aAJDaA?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div></figure>



<p>You are given an array&nbsp;<code>start</code>&nbsp;where&nbsp;<code>start = [startX, startY]</code>&nbsp;represents your initial position&nbsp;<code>(startX, startY)</code>&nbsp;in a 2D space. You are also given the array&nbsp;<code>target</code>&nbsp;where&nbsp;<code>target = [targetX, targetY]</code>&nbsp;represents your target position&nbsp;<code>(targetX, targetY)</code>.</p>



<p>The cost of going from a position&nbsp;<code>(x1, y1)</code>&nbsp;to any other position in the space&nbsp;<code>(x2, y2)</code>&nbsp;is&nbsp;<code>|x2 - x1| + |y2 - y1|</code>.</p>



<p>There are also some special roads. You are given a 2D array&nbsp;<code>specialRoads</code>&nbsp;where&nbsp;<code>specialRoads[i] = [x1<sub>i</sub>, y1<sub>i</sub>, x2<sub>i</sub>, y2<sub>i</sub>, cost<sub>i</sub>]</code>&nbsp;indicates that the&nbsp;<code>i<sup>th</sup></code>&nbsp;special road can take you from&nbsp;<code>(x1<sub>i</sub>, y1<sub>i</sub>)</code>&nbsp;to&nbsp;<code>(x2<sub>i</sub>, y2<sub>i</sub>)</code>&nbsp;with a cost equal to&nbsp;<code>cost<sub>i</sub></code>. You can use each special road any number of times.</p>



<p>Return&nbsp;<em>the minimum cost required to go from</em>&nbsp;<code>(startX, startY)</code>&nbsp;to&nbsp;<code>(targetX, targetY)</code>.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> start = [1,1], target = [4,5], specialRoads = [[1,2,3,3,2],[3,4,4,5,1]]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The optimal path from (1,1) to (4,5) is the following:
- (1,1) -&gt; (1,2). This move has a cost of |1 - 1| + |2 - 1| = 1.
- (1,2) -&gt; (3,3). This move uses the first special edge, the cost is 2.
- (3,3) -&gt; (3,4). This move has a cost of |3 - 3| + |4 - 3| = 1.
- (3,4) -&gt; (4,5). This move uses the second special edge, the cost is 1.
So the total cost is 1 + 2 + 1 + 1 = 5.
It can be shown that we cannot achieve a smaller total cost than 5.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> start = [3,2], target = [5,7], specialRoads = [[3,2,3,4,4],[3,3,5,5,5],[3,4,5,6,6]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> It is optimal to not use any special edges and go directly from the starting to the ending position with a cost |5 - 3| + |7 - 2| = 7.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>start.length == target.length == 2</code></li><li><code>1 &lt;= startX &lt;= targetX &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= startY &lt;= targetY &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= specialRoads.length &lt;= 200</code></li><li><code>specialRoads[i].length == 5</code></li><li><code>startX &lt;= x1<sub>i</sub>, x2<sub>i</sub> &lt;= targetX</code></li><li><code>startY &lt;= y1<sub>i</sub>, y2<sub>i</sub> &lt;= targetY</code></li><li><code>1 &lt;= cost<sub>i</sub> &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Dijkstra</strong></h2>



<ol><li>Create a node for each point in special edges as well as start and target. </li><li>Add edges for special roads (note it&#8217;s directional)</li><li>Add edges for each pair of node with default cost, i.e. |x1-x2| + |y1-y2|</li><li>Run Dijkstra&#8217;s algorithm</li></ol>



<p>Time complexity: O(n<sup>2</sup>logn)<br>Space complexity: O(n<sup>2</sup>)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumCost(vector&lt;int&gt;&amp; start, vector&lt;int&gt;&amp; target, vector&lt;vector&lt;int&gt;&gt;&amp; specialRoads) {
    unordered_map&lt;long, int&gt; ids;
    vector&lt;pair&lt;int, int&gt;&gt; pos;
    
    auto getId = [&amp;](int x, int y) {
      const auto key = ((unsigned long)x &lt;&lt; 32) | y;
      if (ids.count(key)) return ids[key];
      const int id = ids.size();      
      ids[key] = id;
      pos.emplace_back(x, y);
      return id;
    };
    const int s = getId(start[0], start[1]);
    const int t = getId(target[0], target[1]);
    vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; g;
    auto addEdge = [&amp;](int x1, int y1, int x2, int y2, int c = INT_MAX) {      
      int n1 = getId(x1, y1);
      int n2 = getId(x2, y2);
      if (n1 == n2) return;
      while (g.size() &lt;= max(n1, n2)) g.push_back({});      
      int cost = min(c, abs(x1 - x2) + abs(y1 - y2));
      g[n1].emplace_back(cost, n2);
      // directional for special edge
      if (c == INT_MAX) g[n2].emplace_back(cost, n1);
    };
    for (const auto&amp; r : specialRoads)
      addEdge(r[0], r[1], r[2], r[3], r[4]);    
    for (int i = 0; i &lt; pos.size(); ++i)
      for (int j = i + 1; j &lt; pos.size(); ++j)
        addEdge(pos[i].first, pos[i].second, 
                pos[j].first, pos[j].second);
    vector&lt;int&gt; dist(ids.size(), INT_MAX);
    dist[s] = 0;
    priority_queue&lt;pair&lt;int, int&gt;, vector&lt;pair&lt;int, int&gt;&gt;, greater&lt;&gt;&gt; q;
    q.emplace(0, s);    
    while (!q.empty()) {
      auto [d, u] = q.top(); q.pop();
      if (d &gt; dist[u]) continue;
      if (u == t) return d;
      for (auto [c, v] : g[u])
        if (d + c &lt; dist[v])
          q.emplace(dist[v] = d + c, v);
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2662-minimum-cost-of-a-path-with-special-roads/">花花酱 LeetCode 2662. Minimum Cost of a Path With Special Roads</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-2662-minimum-cost-of-a-path-with-special-roads/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2642. Design Graph With Shortest Path Calculator</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2642-design-graph-with-shortest-path-calculator/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2642-design-graph-with-shortest-path-calculator/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Apr 2023 19:16:35 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[dijkstra]]></category>
		<category><![CDATA[floyd-warshall]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10015</guid>

					<description><![CDATA[<p>There is a&#160;directed weighted&#160;graph that consists of&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n - 1. The edges of the graph are initially represented by the given array&#160;edges&#160;where&#160;edges[i] = [fromi,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2642-design-graph-with-shortest-path-calculator/">花花酱 LeetCode 2642. Design Graph With Shortest Path Calculator</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a&nbsp;<strong>directed weighted</strong>&nbsp;graph that consists of&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>. The edges of the graph are initially represented by the given array&nbsp;<code>edges</code>&nbsp;where&nbsp;<code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, edgeCost<sub>i</sub>]</code>&nbsp;meaning that there is an edge from&nbsp;<code>from<sub>i</sub></code>&nbsp;to&nbsp;<code>to<sub>i</sub></code>&nbsp;with the cost&nbsp;<code>edgeCost<sub>i</sub></code>.</p>



<p>Implement the&nbsp;<code>Graph</code>&nbsp;class:</p>



<ul><li><code>Graph(int n, int[][] edges)</code>&nbsp;initializes the object with&nbsp;<code>n</code>&nbsp;nodes and the given edges.</li><li><code>addEdge(int[] edge)</code>&nbsp;adds an edge to the list of edges where&nbsp;<code>edge = [from, to, edgeCost]</code>. It is guaranteed that there is no edge between the two nodes before adding this one.</li><li><code>int shortestPath(int node1, int node2)</code>&nbsp;returns the&nbsp;<strong>minimum</strong>&nbsp;cost of a path from&nbsp;<code>node1</code>&nbsp;to&nbsp;<code>node2</code>. If no path exists, return&nbsp;<code>-1</code>. The cost of a path is the sum of the costs of the edges in the path.</li></ul>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2023/01/11/graph3drawio-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input</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]]
<strong>Output</strong>
[null, 6, -1, null, 6]
</pre>



<p><strong>Explanation</strong> </p>



<pre class="wp-block-preformatted;crayon:false">Graph g = new Graph(4, [[0, 2, 5], [0, 1, 2], [1, 2, 1], [3, 0, 3]]); g.shortestPath(3, 2); // return 6. The shortest path from 3 to 2 in the first diagram above is 3 -> 0 -> 1 -> 2 with a total cost of 3 + 2 + 1 = 6.
g.shortestPath(0, 3); // return -1. There is no path from 0 to 3. 
g.addEdge([1, 3, 4]); // We add an edge from node 1 to node 3, and we get the second diagram above. 
g.shortestPath(0, 3); // return 6. The shortest path from 0 to 3 now is 0 -> 1 -> 3 with a total cost of 2 + 4 = 6.</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 100</code></li><li><code>0 &lt;= edges.length &lt;= n * (n - 1)</code></li><li><code>edges[i].length == edge.length == 3</code></li><li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>, from, to, node1, node2 &lt;= n - 1</code></li><li><code>1 &lt;= edgeCost<sub>i</sub>, edgeCost &lt;= 10<sup>6</sup></code></li><li>There are no repeated edges and no self-loops in the graph at any point.</li><li>At most&nbsp;<code>100</code>&nbsp;calls will be made for&nbsp;<code>addEdge</code>.</li><li>At most&nbsp;<code>100</code>&nbsp;calls will be made for&nbsp;<code>shortestPath</code>.</li></ul>



<h2><strong>Solution 1: Floyd-Washall</strong></h2>



<p>Time complexity:<br>Init O(n<sup>3</sup>)<br>addEdge O(n<sup>2</sup>)<br>shortestPath O(1)</p>



<p>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Graph {
public:
  Graph(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges):
  n_(n),
  d_(n, vector&lt;long&gt;(n, 1e18)) {
    for (int i = 0; i &lt; n; ++i)
      d_[i][i] = 0;
    for (const vector&lt;int&gt;&amp; e : edges)
      d_[e[0]][e[1]] = e[2];    
    for (int k = 0; k &lt; n; ++k)
      for (int i = 0; i &lt; n; ++i)
        for (int j = 0; j &lt; n; ++j)
          d_[i][j] = min(d_[i][j], d_[i][k] + d_[k][j]);
  }
  
  void addEdge(vector&lt;int&gt; edge) {    
    for (int i = 0; i &lt; n_; ++i)
      for (int j = 0; j &lt; n_; ++j)
        d_[i][j] = min(d_[i][j], d_[i][edge[0]] + edge[2] + d_[edge[1]][j]);
  }
  
  int shortestPath(int node1, int node2) {
    return d_[node1][node2] &gt;= 1e18 ? -1 : d_[node1][node2];
  }
private:
  int n_;
  vector&lt;vector&lt;long&gt;&gt; d_;
};</pre>
</div></div>



<h2><strong>Solution 2: Dijkstra</strong></h2>



<p>Time complexity: <br>Init: O(|E|) ~ O(n<sup>2</sup>)<br>AddEdge: O(1)<br>ShortestPath: O(|V|*log(|E|)) ~ O(n*logn)</p>



<p>Space complexity: O(E|) ~ O(n<sup>2</sup>)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Graph {
public:
    Graph(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges): n_(n), g_(n) {
      for (const auto&amp; e : edges)
        g_[e[0]].emplace_back(e[1], e[2]);
    }
    
    void addEdge(vector&lt;int&gt; edge) {
      g_[edge[0]].emplace_back(edge[1], edge[2]);
    }
    
    int shortestPath(int node1, int node2) {
      vector&lt;int&gt; dist(n_, INT_MAX);
      dist[node1] = 0;
      priority_queue&lt;pair&lt;int, int&gt;, vector&lt;pair&lt;int, int&gt;&gt;, greater&lt;&gt;&gt; q;
      q.emplace(0, node1);
      while (!q.empty()) {
        const auto [d, u] = q.top(); q.pop();        
        if (u == node2) return d;
        for (const auto&amp; [v, c] : g_[u])
          if (dist[u] + c &lt; dist[v]) {
            dist[v] = dist[u] + c;
            q.emplace(dist[v], v);
          }
      }
      return -1;
    }
private:
  int n_;
  vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; g_;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2642-design-graph-with-shortest-path-calculator/">花花酱 LeetCode 2642. Design Graph With Shortest Path Calculator</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-2642-design-graph-with-shortest-path-calculator/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1786. Number of Restricted Paths From First to Last Node</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1786-number-of-restricted-paths-from-first-to-last-node/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1786-number-of-restricted-paths-from-first-to-last-node/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Mar 2021 07:30:38 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[dijkstra]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8219</guid>

					<description><![CDATA[<p>There is an undirected weighted connected graph. You are given a positive integer&#160;n&#160;which denotes that the graph has&#160;n&#160;nodes labeled from&#160;1&#160;to&#160;n, and an array&#160;edges&#160;where each&#160;edges[i] =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1786-number-of-restricted-paths-from-first-to-last-node/">花花酱 LeetCode 1786. Number of Restricted Paths From First to Last Node</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1786. Number of Restricted Paths From First to Last Node - 刷题找工作 EP388" width="500" height="281" src="https://www.youtube.com/embed/1VN6h1sohAs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There is an undirected weighted connected graph. You are given a positive integer&nbsp;<code>n</code>&nbsp;which denotes that the graph has&nbsp;<code>n</code>&nbsp;nodes labeled from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>, and an array&nbsp;<code>edges</code>&nbsp;where each&nbsp;<code>edges[i] = [u<sub>i</sub>, v<sub>i</sub>, weight<sub>i</sub>]</code>&nbsp;denotes that there is an edge between nodes&nbsp;<code>u<sub>i</sub></code>&nbsp;and&nbsp;<code>v<sub>i</sub></code>&nbsp;with weight equal to&nbsp;<code>weight<sub>i</sub></code>.</p>



<p>A path from node&nbsp;<code>start</code>&nbsp;to node&nbsp;<code>end</code>&nbsp;is a sequence of nodes&nbsp;<code>[z<sub>0</sub>, z<sub>1</sub>,z<sub>2</sub>, ..., z<sub>k</sub>]</code>&nbsp;such that&nbsp;<code>z<sub>0&nbsp;</sub>= start</code>&nbsp;and&nbsp;<code>z<sub>k</sub>&nbsp;= end</code>&nbsp;and there is an edge between&nbsp;<code>z<sub>i</sub></code>&nbsp;and&nbsp;<code>z<sub>i+1</sub></code>&nbsp;where&nbsp;<code>0 &lt;= i &lt;= k-1</code>.</p>



<p>The distance of a path is the sum of the weights on the edges of the path. Let&nbsp;<code>distanceToLastNode(x)</code>&nbsp;denote the shortest distance of a path between node&nbsp;<code>n</code>&nbsp;and node&nbsp;<code>x</code>. A&nbsp;<strong>restricted path</strong>&nbsp;is a path that also satisfies that&nbsp;<code>distanceToLastNode(z<sub>i</sub>) &gt; distanceToLastNode(z<sub>i+1</sub>)</code>&nbsp;where&nbsp;<code>0 &lt;= i &lt;= k-1</code>.</p>



<p>Return&nbsp;<em>the number of restricted paths from node</em>&nbsp;<code>1</code>&nbsp;<em>to node</em>&nbsp;<code>n</code>. Since that number may be too large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> Each circle contains the node number in black and its <code>distanceToLastNode value in blue. </code>The three restricted paths are:
1) 1 --&gt; 2 --&gt; 5
2) 1 --&gt; 2 --&gt; 3 --&gt; 5
3) 1 --&gt; 3 --&gt; 5
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/02/17/restricted_paths_ex22.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[1,3,1],[4,1,2],[7,3,4],[2,5,3],[5,6,1],[6,7,2],[7,5,3],[2,6,4]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each circle contains the node number in black and its <code>distanceToLastNode value in blue. </code>The only restricted path is 1 --&gt; 3 --&gt; 7.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li><li><code>n - 1 &lt;= edges.length &lt;= 4 * 10<sup>4</sup></code></li><li><code>edges[i].length == 3</code></li><li><code>1 &lt;= u<sub>i</sub>, v<sub>i</sub>&nbsp;&lt;= n</code></li><li><code>u<sub>i&nbsp;</sub>!= v<sub>i</sub></code></li><li><code>1 &lt;= weight<sub>i</sub>&nbsp;&lt;= 10<sup>5</sup></code></li><li>There is at most one edge between any two nodes.</li><li>There is at least one path between any two nodes.</li></ul>



<h2><strong>Solution: Dijkstra + DFS w/ memoization</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-1.png" alt="" class="wp-image-8225" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Find shortest path from n to all the nodes.<br>paths(u) = sum(paths(v)) if dist[u] &gt; dist[v] and (u, v) has an edge<br>return paths(1)</p>



<p>Time complexity: O(ElogV + V + E)<br>Space complexity: O(V + E)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countRestrictedPaths(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    constexpr int kMod = 1e9 + 7;
    using PII = pair&lt;int, int&gt;;    
    vector&lt;vector&lt;PII&gt;&gt; g(n + 1);
    for (const auto&amp; e : edges) {
      g[e[0]].emplace_back(e[1], e[2]);
      g[e[1]].emplace_back(e[0], e[2]);
    }    
    
    // Shortest distance from n to x.
    vector&lt;int&gt; dist(n + 1, INT_MAX / 2);
    dist[n] = 0;
    priority_queue&lt;PII, vector&lt;PII&gt;, std::greater&lt;PII&gt;&gt; q;
    q.emplace(0, n);
    while (!q.empty()) {
      const auto [d, u] = q.top(); q.pop();
      if (dist[u] &lt; d) continue;
      for (auto [v, w]: g[u]) {
        if (dist[u] + w &gt;= dist[v]) continue;
        dist[v] = dist[u] + w;
        q.emplace(dist[v], v);
      }
    }

    vector&lt;int&gt; dp(n + 1, INT_MAX);
    function&lt;int(int)&gt; dfs = [&amp;](int u) {      
      if (u == n) return 1;
      if (dp[u] != INT_MAX) return dp[u];
      int ans = 0;
      for (auto [v, w]: g[u])
        if (dist[u] &gt; dist[v])
          ans = (ans + dfs(v)) % kMod;      
      return dp[u] = ans;
    };
    
    return dfs(1);
  }
};</pre>
</div></div>



<p>Combined</p>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-2.png" alt="" class="wp-image-8226" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-3.png" alt="" class="wp-image-8227" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/03/1786-ep388-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countRestrictedPaths(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    constexpr int kMod = 1e9 + 7;
    using PII = pair&lt;int, int&gt;;    
    vector&lt;vector&lt;PII&gt;&gt; g(n + 1);
    for (const auto&amp; e : edges) {
      g[e[0]].emplace_back(e[1], e[2]);
      g[e[1]].emplace_back(e[0], e[2]);
    }    
    
    // Shortest distance from n to x.
    vector&lt;int&gt; dist(n + 1, INT_MAX);
    vector&lt;int&gt; dp(n + 1);
    dist[n] = 0;
    dp[n] = 1;
    priority_queue&lt;PII, vector&lt;PII&gt;, std::greater&lt;PII&gt;&gt; q;
    q.emplace(0, n);
    while (!q.empty()) {
      const auto [d, u] = q.top(); q.pop();
      if (d &gt; dist[u]) continue;
      if (u == 1) break;
      for (auto [v, w]: g[u]) {
        if (dist[v] &gt; dist[u] + w)
          q.emplace(dist[v] = dist[u] + w, v);
        if (dist[v] &gt; dist[u])
          dp[v] = (dp[v] + dp[u]) % kMod;
      }
    }    
    return dp[1];
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1786-number-of-restricted-paths-from-first-to-last-node/">花花酱 LeetCode 1786. Number of Restricted Paths From First to Last Node</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-1786-number-of-restricted-paths-from-first-to-last-node/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1514. Path with Maximum Probability</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1514-path-with-maximum-probability/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1514-path-with-maximum-probability/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Jul 2020 05:44:28 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[dijkstra]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7079</guid>

					<description><![CDATA[<p>You are given an undirected weighted graph of&#160;n&#160;nodes (0-indexed), represented by an edge list where&#160;edges[i] = [a, b]&#160;is an undirected edge connecting the nodes&#160;a&#160;and&#160;b&#160;with a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1514-path-with-maximum-probability/">花花酱 LeetCode 1514. Path with Maximum Probability</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an undirected weighted graph of&nbsp;<code>n</code>&nbsp;nodes (0-indexed), represented by an edge list where&nbsp;<code>edges[i] = [a, b]</code>&nbsp;is an undirected edge connecting the nodes&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>&nbsp;with a probability of success of traversing that edge&nbsp;<code>succProb[i]</code>.</p>



<p>Given two nodes&nbsp;<code>start</code>&nbsp;and&nbsp;<code>end</code>, find the path with the maximum probability of success to go from&nbsp;<code>start</code>&nbsp;to&nbsp;<code>end</code>&nbsp;and return its success probability.</p>



<p>If there is no path from&nbsp;<code>start</code>&nbsp;to&nbsp;<code>end</code>,&nbsp;<strong>return&nbsp;0</strong>. Your answer will be accepted if it differs from the correct answer by at most&nbsp;<strong>1e-5</strong>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/09/20/1558_ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
<strong>Output:</strong> 0.25000
<strong>Explanation:</strong>&nbsp;There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/09/20/1558_ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
<strong>Output:</strong> 0.30000
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/09/20/1558_ex3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
<strong>Output:</strong> 0.00000
<strong>Explanation:</strong>&nbsp;There is no path between 0 and 2.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= n &lt;= 10^4</code></li><li><code>0 &lt;= start, end &lt; n</code></li><li><code>start != end</code></li><li><code>0 &lt;= a, b &lt; n</code></li><li><code>a != b</code></li><li><code>0 &lt;= succProb.length == edges.length &lt;= 2*10^4</code></li><li><code>0 &lt;= succProb[i] &lt;= 1</code></li><li>There is at most one edge between every two nodes.</li></ul>



<h2><strong>Solution: Dijkstra&#8217;s Algorithm</strong></h2>



<p>max(P1*P2*&#8230;*Pn) =&gt; max(log(P1*P2&#8230;*Pn)) =&gt; max(log(P1) + log(P2) + &#8230; + log(Pn) =&gt; min(-(log(P1) + log(P2) &#8230; + log(Pn)).</p>



<p>Thus we can convert this problem to the classic single source shortest path problem that can be solved with Dijkstra&#8217;s algorithm.</p>



<p>Time complexity: O(ElogV)<br>Space complexity: O(E+V)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Author: Huahua
class Solution {
public:
  double maxProbability(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, 
                        vector&lt;double&gt;&amp; succProb, int start, int end) {
    vector&lt;vector&lt;pair&lt;int, double&gt;&gt;&gt; g(n); // u -&gt; {v, -log(w)}
    for (int i = 0; i &lt; edges.size(); ++i) {
      const double w = -log(succProb[i]);
      g[edges[i][0]].emplace_back(edges[i][1], w);
      g[edges[i][1]].emplace_back(edges[i][0], w);
    }

    vector&lt;double&gt; dist(n, FLT_MAX);
    priority_queue&lt;pair&lt;double, int&gt;&gt; q;
    q.emplace(-0.0, start);
    vector&lt;int&gt; seen(n);
    while (!q.empty()) {
      const double d = -q.top().first;
      const int u = q.top().second;        
      q.pop();
      seen[u] = 1;
      if (u == end) return exp(-d);
      for (const auto&amp; [v, w] : g[u]) {
        if (seen[v] || d + w &gt; dist[v]) continue;
        q.emplace(-(dist[v] = d + w), v);
      }
    }
    return 0;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
import java.util.AbstractMap;

class Solution {
  public double maxProbability(int n, int[][] edges, double[] succProb, int start, int end) {
    var g = new ArrayList&lt;List&lt;Map.Entry&lt;Integer, Double&gt;&gt;&gt;();
    for (int i = 0; i &lt; n; ++i) g.add(new ArrayList&lt;Map.Entry&lt;Integer, Double&gt;&gt;());
    for (int i = 0; i &lt; edges.length; ++i) {
      g.get(edges[i][0]).add(new AbstractMap.SimpleEntry&lt;&gt;(edges[i][1], -Math.log(succProb[i])));
      g.get(edges[i][1]).add(new AbstractMap.SimpleEntry&lt;&gt;(edges[i][0], -Math.log(succProb[i])));
    }    
    var seen = new boolean[n];
    var dist = new double[n];
    Arrays.fill(dist, Double.MAX_VALUE);
    seen[start] = true;
    dist[start] = 0.0;
    // {u, dist[u]}
    var q = new PriorityQueue&lt;Map.Entry&lt;Integer, Double&gt;&gt;(Map.Entry.comparingByValue());    
    q.offer(new AbstractMap.SimpleEntry&lt;&gt;(start, 0.0));
    while (!q.isEmpty()) {
      var node = q.poll();
      final int u = node.getKey();
      if (u == end) return Math.exp(-dist[end]);
      seen[u] = true;
      for (var e : g.get(u)) {
        final int v = e.getKey();
        final double w = e.getValue();
        if (seen[v] || dist[u] + w &gt; dist[v]) continue;
        dist[v] = dist[u] + w;
        q.offer(new AbstractMap.SimpleEntry&lt;&gt;(v, dist[v]));
      }
    }
    return 0;
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def maxProbability(self, n: int, edges: List[List[int]], 
                     succProb: List[float], start: int, end: int) -&gt; float:
    g = [[] for _ in range(n)]
    for i, e in enumerate(edges):
      g[e[0]].append((e[1], -math.log(succProb[i])))
      g[e[1]].append((e[0], -math.log(succProb[i])))
    seen = [False] * n
    dist = [float('inf')] * n
    dist[start] = 0.0
    q = [(dist[start], start)]
    while q:
      _, u = heapq.heappop(q)
      if seen[u]: continue
      seen[u] = True
      if u == end: return math.exp(-dist[u])
      for v, w in g[u]:
        if seen[v] or dist[u] + w &gt; dist[v]: continue
        dist[v] = dist[u] + w        
        heapq.heappush(q, (dist[v], v))
    return 0</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1514-path-with-maximum-probability/">花花酱 LeetCode 1514. Path with Maximum Probability</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-1514-path-with-maximum-probability/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 27 Jan 2020 06:58:54 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[dijkstra]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[floyd-warshall]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^3)]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6149</guid>

					<description><![CDATA[<p>There are&#160;n&#160;cities numbered from&#160;0&#160;to&#160;n-1. Given the array&#160;edges&#160;where&#160;edges[i] = [fromi, toi, weighti]&#160;represents a bidirectional and weighted edge between cities&#160;fromi&#160;and&#160;toi, and given the integer&#160;distanceThreshold. Return the city&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/">花花酱 LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1334. Find the City With the Smallest Number of Neighbors - 刷题找工作 EP303" width="500" height="375" src="https://www.youtube.com/embed/iE0tJ-8rPLQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There are&nbsp;<code>n</code>&nbsp;cities numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n-1</code>. Given the array&nbsp;<code>edges</code>&nbsp;where&nbsp;<code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>, weight<sub>i</sub>]</code>&nbsp;represents a bidirectional and weighted edge between cities&nbsp;<code>from<sub>i</sub></code>&nbsp;and&nbsp;<code>to<sub>i</sub></code>, and given the integer&nbsp;<code>distanceThreshold</code>.</p>



<p>Return the city with the smallest numberof&nbsp;cities that are reachable through some path and whose distance is&nbsp;<strong>at most</strong>&nbsp;<code>distanceThreshold</code>, If there are multiple such cities, return the city with the greatest number.</p>



<p>Notice that the distance of a path connecting cities&nbsp;<em><strong>i</strong></em>&nbsp;and&nbsp;<em><strong>j</strong></em>&nbsp;is equal to the sum of the edges&#8217; weights along that path.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/16/find_the_city_01.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]], distanceThreshold = 4
<strong>Output:</strong> 3
<strong>Explanation: </strong>The figure above describes the graph.&nbsp;
The neighboring cities at a distanceThreshold = 4 for each city are:
City 0 -&gt; [City 1, City 2]&nbsp;
City 1 -&gt; [City 0, City 2, City 3]&nbsp;
City 2 -&gt; [City 0, City 1, City 3]&nbsp;
City 3 -&gt; [City 1, City 2]&nbsp;
Cities 0 and 3 have 2 neighboring cities at a distanceThreshold = 4, but we have to return city 3 since it has the greatest number.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/01/16/find_the_city_02.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, edges = [[0,1,2],[0,4,8],[1,2,3],[1,4,2],[2,3,1],[3,4,1]], distanceThreshold = 2
<strong>Output:</strong> 0
<strong>Explanation: </strong>The figure above describes the graph.&nbsp;
The neighboring cities at a distanceThreshold = 2 for each city are:
City 0 -&gt; [City 1]&nbsp;
City 1 -&gt; [City 0, City 4]&nbsp;
City 2 -&gt; [City 3, City 4]&nbsp;
City 3 -&gt; [City 2, City 4]
City 4 -&gt; [City 1, City 2, City 3]&nbsp;
The city 0 has 1 neighboring city at a distanceThreshold = 2.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>2 &lt;= n &lt;= 100</code></li><li><code>1 &lt;= edges.length &lt;= n * (n - 1) / 2</code></li><li><code>edges[i].length == 3</code></li><li><code>0 &lt;= from<sub>i</sub>&nbsp;&lt; to<sub>i</sub>&nbsp;&lt; n</code></li><li><code>1 &lt;= weight<sub>i</sub>,&nbsp;distanceThreshold &lt;= 10^4</code></li><li>All pairs&nbsp;<code>(from<sub>i</sub>, to<sub>i</sub>)</code>&nbsp;are distinct.</li></ul>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/01/1334-ep303-1.png" alt="" class="wp-image-6163" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/01/1334-ep303-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/01/1334-ep303-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/01/1334-ep303-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<h2><strong>Solution1: Floyd-Warshall</strong></h2>



<p>All pair shortest path</p>



<p>Time complexity: O(n^3)<br>Space complexity: O(n^2)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findTheCity(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, int distanceThreshold) {
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, INT_MAX / 2));
    for (const auto&amp; e : edges)      
      dp[e[0]][e[1]] = dp[e[1]][e[0]] = e[2];    
    
    for (int k = 0; k &lt; n; ++k)
      for (int u = 0; u &lt; n; ++u)
        for (int v = 0; v &lt; n; ++v)
          dp[u][v] = min(dp[u][v], dp[u][k] + dp[k][v]);
    
    int ans = -1;
    int min_nb = INT_MAX;
    for (int u = 0; u &lt; n; ++u) {
      int nb = 0;
      for (int v = 0; v &lt; n; ++v)
        if (v != u &amp;&amp; dp[u][v] &lt;= distanceThreshold)
          ++nb;
      if (nb &lt;= min_nb) {
        min_nb = nb;
        ans = u;
      }
    }
    
    return ans;
  }
};</pre>
</div></div>



<p><strong>Solution 2: Dijkstra&#8217;s Algorithm</strong></p>



<p>Time complexity: O(V * ElogV) / worst O(n^3*logn), best O(n^2*logn)<br>Space complexity: O(V + E)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
// Author: Huahua
class Solution {
public:
  int findTheCity(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges, int t) {
    vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; g(n);
    for (const auto&amp; e : edges) {
      g[e[0]].emplace_back(e[1], e[2]);
      g[e[1]].emplace_back(e[0], e[2]);
    }
    
    // Returns the number of nodes within t from s.
    auto dijkstra = [&amp;](int s) {
      vector&lt;int&gt; dist(n, INT_MAX / 2);
      set&lt;pair&lt;int, int&gt;&gt; q; // &lt;dist, node&gt;
      vector&lt;set&lt;pair&lt;int, int&gt;&gt;::const_iterator&gt; its(n);
      dist[s] = 0;
      for (int i = 0; i &lt; n; ++i)
        its[i] = q.emplace(dist[i], i).first;
      while (!q.empty()) {
        auto it = cbegin(q);
        int d = it-&gt;first;
        int u = it-&gt;second;
        q.erase(it);        
        if (d &gt; t) break; // pruning
        for (const auto&amp; p : g[u]) {
          int v = p.first;
          int w = p.second;
          if (dist[v] &lt;= d + w) continue;
          // Decrease key
          q.erase(its[v]);
          its[v] = q.emplace(dist[v] = d + w, v).first;
        }
      }
      return count_if(begin(dist), end(dist), [t](int d) { return d &lt;= t; });
    };
    
    int ans = -1;
    int min_nb = INT_MAX;
    for (int i = 0; i &lt; n; ++i) {
      int nb = dijkstra(i);
      if (nb &lt;= min_nb) {
        min_nb = nb;
        ans = i;
      }
    }
    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/">花花酱 LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-1334-find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
