<?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>floyd-warshall Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/floyd-warshall/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/floyd-warshall/</link>
	<description></description>
	<lastBuildDate>Sat, 29 Apr 2023 19:33:18 +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>floyd-warshall Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/floyd-warshall/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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 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>
