<?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>O(n^2) Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/on2/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/on2/</link>
	<description></description>
	<lastBuildDate>Fri, 03 Jan 2020 05:23:36 +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>O(n^2) Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/on2/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1301. Number of Paths with Max Score</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1301-number-of-paths-with-max-score/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1301-number-of-paths-with-max-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 28 Dec 2019 18:20:16 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[board]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6001</guid>

					<description><![CDATA[<p>You are given a square&#160;board&#160;of characters. You can move on the board starting at the bottom right square marked with the character&#160;'S'. You need&#160;to reach&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1301-number-of-paths-with-max-score/">花花酱 LeetCode 1301. Number of Paths with Max Score</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 1301. Number of Paths with Max Score - 刷题找工作 EP289" width="500" height="375" src="https://www.youtube.com/embed/WwdjLkWmDPs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a square&nbsp;<code>board</code>&nbsp;of characters. You can move on the board starting at the bottom right square marked with the character&nbsp;<code>'S'</code>.</p>



<p>You need&nbsp;to reach the top left square marked with the character&nbsp;<code>'E'</code>. The rest of the squares are labeled either with a numeric character&nbsp;<code>1, 2, ..., 9</code>&nbsp;or with an obstacle&nbsp;<code>'X'</code>. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there.</p>



<p>Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum,&nbsp;<strong>taken modulo&nbsp;<code>10^9 + 7</code></strong>.</p>



<p>In case there is no path, return&nbsp;<code>[0, 0]</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> board = ["E23","2X2","12S"]
<strong>Output:</strong> [7,1]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> board = ["E12","1X1","21S"]
<strong>Output:</strong> [4,2]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> board = ["E11","XXX","11S"]
<strong>Output:</strong> [0,0]
</pre>



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



<ul><li><code>2 &lt;= board.length == board[i].length &lt;= 100</code></li></ul>



<h2><strong>Solution: DP</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1301-ep299.png" alt="" class="wp-image-6007" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1301-ep299.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1301-ep299-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/12/1301-ep299-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i][j] := max score when reach (j, i)<br>count[i][j] := path to reach (j, i) with max score<br><br>m = max(dp[i + 1][j], dp[i][j+1], dp[i+1][j+1])<br>dp[i][j] = board[i][j] + m<br>count[i][j] += count[i+1][j] if dp[i+1][j] == m<br>count[i][j] += count[i][j+1] if dp[i][j+1] == m<br>count[i][j] += count[i+1][j+1] if dp[i+1][j+1] == m</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; pathsWithMaxScore(vector&lt;string&gt;&amp; board) {
    constexpr int kMod = 1e9 + 7;
    const int n = board.size();
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(n + 1));
    vector&lt;vector&lt;int&gt;&gt; cc(n + 1, vector&lt;int&gt;(n + 1, 0));
    board[n - 1][n - 1] = board[0][0] = '0';
    cc[n - 1][n - 1] = 1;
    for (int i = n - 1; i &gt;= 0; --i)
      for (int j = n - 1; j &gt;= 0; --j) {
        if (board[i][j] != 'X') {          
          int m = max({dp[i + 1][j], dp[i][j + 1], dp[i + 1][j + 1]});
          dp[i][j] = (board[i][j] - '0') + m;
          if (dp[i + 1][j] == m) 
            cc[i][j] = (cc[i][j] + cc[i + 1][j]) % kMod;
          if (dp[i][j + 1] == m)
            cc[i][j] = (cc[i][j] + cc[i][j + 1]) % kMod;
          if (dp[i + 1][j + 1] == m)
            cc[i][j] = (cc[i][j] + cc[i + 1][j + 1]) % kMod;
        }
      }
    return {cc[0][0] ? dp[0][0] : 0, cc[0][0]};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1301-number-of-paths-with-max-score/">花花酱 LeetCode 1301. Number of Paths with Max Score</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/dynamic-programming/leetcode-1301-number-of-paths-with-max-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1230. Toss Strange Coins</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1230-toss-strange-coins/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1230-toss-strange-coins/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 20 Oct 2019 04:05:29 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5771</guid>

					<description><![CDATA[<p>You have some coins.&#160; The&#160;i-th&#160;coin has a probability&#160;prob[i]&#160;of facing heads when tossed. Return the probability that the number of coins facing heads equals&#160;target&#160;if you toss&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1230-toss-strange-coins/">花花酱 LeetCode 1230. Toss Strange Coins</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 have some coins.&nbsp; The&nbsp;<code>i</code>-th&nbsp;coin has a probability&nbsp;<code>prob[i]</code>&nbsp;of facing heads when tossed.</p>



<p>Return the probability that the number of coins facing heads equals&nbsp;<code>target</code>&nbsp;if you toss every coin exactly once.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prob = [0.4], target = 1
<strong>Output:</strong> 0.40000
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prob = [0.5,0.5,0.5,0.5,0.5], target = 0
<strong>Output:</strong> 0.03125
</pre>



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



<ul><li><code>1 &lt;= prob.length &lt;= 1000</code></li><li><code>0 &lt;= prob[i] &lt;= 1</code></li><li><code>0 &lt;= target&nbsp;</code><code>&lt;= prob.length</code></li><li>Answers will be accepted as correct if they are within&nbsp;<code>10^-5</code>&nbsp;of the correct answer.</li></ul>



<h2><strong>Solution: DP</strong></h2>



<p>dp[i][j] := prob of j coins face up after tossing first i coins.<br>dp[i][j] = dp[i-1][j] * (1 &#8211; p[i]) + dp[i-1][j-1] * p[i]</p>



<p>Time complexity: O(n^2)<br>Space complexity: O(n^2) -&gt; O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double probabilityOfHeads(vector&lt;double&gt;&amp; prob, int target) {
    const int n = prob.size();
    vector&lt;double&gt; dp(target + 1);    
    dp[0] = 1.0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = min(i + 1, target); j &gt;= 0; --j)
        dp[j] = dp[j] * (1 - prob[i]) + (j &gt; 0 ? dp[j - 1] : 0) * prob[i];
    return dp[target];
  }
};</pre>
</div></div>



<p>Solution 2: Recursion + Memorization</p>



<p>Time complexity: O(n^2)<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:
  double probabilityOfHeads(vector&lt;double&gt;&amp; prob, int target) {    
    vector&lt;vector&lt;double&gt;&gt; mem(prob.size() + 1, vector&lt;double&gt;(target + 1, -1)); 
    function&lt;double(int, int)&gt; dp = [&amp;](int n, int k) {
      if (k &gt; n || k &lt; 0) return 0.0;      
      if (n == 0) return 1.0;
      if (mem[n][k] &gt;= 0) return mem[n][k];
      const double p = prob[n - 1];
      return mem[n][k] = p * dp(n - 1, k - 1) + (1 - p) * dp(n - 1, k);
    };    
    return dp(prob.size(), target);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1230-toss-strange-coins/">花花酱 LeetCode 1230. Toss Strange Coins</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/dynamic-programming/leetcode-1230-toss-strange-coins/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 48. Rotate Image</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 16:20:55 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[flip]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mirror]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[rotate]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5698</guid>

					<description><![CDATA[<p>You are given an&#160;n&#160;x&#160;n&#160;2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image&#160;in-place, which means you&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/">花花酱 LeetCode 48. Rotate Image</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&nbsp;<em>n</em>&nbsp;x&nbsp;<em>n</em>&nbsp;2D matrix representing an image.</p>



<p>Rotate the image by 90 degrees (clockwise).</p>



<p><strong>Note:</strong></p>



<p>You have to rotate the image&nbsp;<a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noreferrer noopener"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly.&nbsp;<strong>DO NOT</strong>&nbsp;allocate another 2D matrix and do the rotation.</p>



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



<pre class="wp-block-preformatted;crayon:false">Given <strong>input matrix</strong> = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix <strong>in-place</strong> such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
</pre>



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



<pre class="wp-block-preformatted;crayon:false">Given <strong>input matrix</strong> =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix <strong>in-place</strong> such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]</pre>



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



<p>First pass: mirror around diagonal <br>Second pass: mirror around y axis</p>



<p>Time complexity: O(n^2)<br>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 Solution {
public:
  void rotate(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int n = matrix.size();
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        swap(matrix[i][j], matrix[j][i]);
    for (int i = 0; i &lt; n; ++i)
      reverse(begin(matrix[i]), end(matrix[i]));
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-48-rotate-image/">花花酱 LeetCode 48. Rotate Image</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/algorithms/array/leetcode-48-rotate-image/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 59. Spiral Matrix II</title>
		<link>https://zxi.mytechroad.com/blog/uncategorized/leetcode-59-spiral-matrix-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/uncategorized/leetcode-59-spiral-matrix-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 03:13:27 +0000</pubDate>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5607</guid>

					<description><![CDATA[<p>Given a positive integer&#160;n, generate a square matrix filled with elements from 1 to&#160;n2&#160;in spiral order. Example: Input: 3 Output: [ [ 1, 2, 3&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-59-spiral-matrix-ii/">花花酱 LeetCode 59. Spiral Matrix II</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>Given a positive integer&nbsp;<em>n</em>, generate a square matrix filled with elements from 1 to&nbsp;<em>n</em><sup>2</sup>&nbsp;in spiral order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 3
<strong>Output:</strong>
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]</pre>



<h2><strong>Solution: Simulation</strong></h2>



<p>Time complexity: O(n^2)<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:
  vector&lt;vector&lt;int&gt; &gt; generateMatrix(int n) {
    vector&lt;vector&lt;int&gt;&gt; ans(n, vector&lt;int&gt;(n));
    int dir = 2, x = 0, y = 0;
    int max_x = n - 1, max_y = n - 1;
    int min_x = 0, min_y = 1;
    int i = 0;

    while (++i &lt;= n*n) {
      ans[y][x] = i;
      switch (dir) {
        // up
        case 1: if (--y == min_y) { dir = 2; ++min_y; } break;
        // right
        case 2: if (++x == max_x) { dir = 3; --max_x; } break;
        // down
        case 3: if (++y == max_y) { dir = 4; --max_y; } break;
        // left
        case 4: if (--x == min_x) { dir = 1; ++min_x; } break;
      }
    }

    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/uncategorized/leetcode-59-spiral-matrix-ii/">花花酱 LeetCode 59. Spiral Matrix II</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/uncategorized/leetcode-59-spiral-matrix-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1210. Minimum Moves to Reach Target with Rotations</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1210-minimum-moves-to-reach-target-with-rotations/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1210-minimum-moves-to-reach-target-with-rotations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Sep 2019 07:58:00 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5601</guid>

					<description><![CDATA[<p>In an&#160;n*n&#160;grid, there is a snake that spans 2 cells and starts moving from the top left corner at&#160;(0, 0)&#160;and&#160;(0, 1). The grid has empty&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1210-minimum-moves-to-reach-target-with-rotations/">花花酱 LeetCode 1210. Minimum Moves to Reach Target with Rotations</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>In an&nbsp;<code>n*n</code>&nbsp;grid, there is a snake that spans 2 cells and starts moving from the top left corner at&nbsp;<code>(0, 0)</code>&nbsp;and&nbsp;<code>(0, 1)</code>. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at&nbsp;<code>(n-1, n-2)</code>&nbsp;and&nbsp;<code>(n-1, n-1)</code>.</p>



<p>In one move the snake can:</p>



<ul><li>Move one cell to the right&nbsp;if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.</li><li>Move down one cell&nbsp;if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is.</li><li>Rotate clockwise if it&#8217;s in a horizontal position and the two cells under it are both empty. In that case the snake moves from&nbsp;<code>(r, c)</code>&nbsp;and&nbsp;<code>(r, c+1)</code>&nbsp;to&nbsp;<code>(r, c)</code>&nbsp;and&nbsp;<code>(r+1, c)</code>.<br></li><li>Rotate counterclockwise&nbsp;if it&#8217;s in a vertical position and the two cells to its right are both empty. In that case the snake moves from&nbsp;<code>(r, c)</code>&nbsp;and&nbsp;<code>(r+1, c)</code>&nbsp;to&nbsp;<code>(r, c)</code>&nbsp;and&nbsp;<code>(r, c+1)</code>.<br></li></ul>



<p>Return the minimum number of moves to reach the target.</p>



<p>If there is no way to reach the target, return&nbsp;<code>-1</code>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[0,0,0,0,0,1],
               [1,1,0,0,1,0],
&nbsp;              [0,0,0,0,1,1],
&nbsp;              [0,0,1,0,1,0],
&nbsp;              [0,1,1,0,0,0],
&nbsp;              [0,1,1,0,0,0]]
<strong>Output:</strong> 11
<strong>Explanation:
</strong>One possible solution is [right, right, rotate clockwise, right, down, down, down, down, rotate counterclockwise, right, down].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[0,0,1,1,1,1],
&nbsp;              [0,0,0,0,1,1],
&nbsp;              [1,1,0,0,0,1],
&nbsp;              [1,1,1,0,0,1],
&nbsp;              [1,1,1,0,0,1],
&nbsp;              [1,1,1,0,0,0]]
<strong>Output:</strong> 9
</pre>



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



<ul><li><code>2 &lt;= n &lt;= 100</code></li><li><code>0 &lt;= grid[i][j] &lt;= 1</code></li><li>It is guaranteed that the snake starts at empty cells.</li></ul>



<h2><strong>Solution1: BFS</strong></h2>



<p>Time complexity: O(n^2)<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, 48 ms, 18.1 MB
class Solution {
public:
  inline int pos(int x, int y) {
    return y * 100 + x;
  }
  
  inline int encode(int p1, int p2) {
    return (p1 &lt;&lt; 16) | p2;
  }
  
  int minimumMoves(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {    
    int n = grid.size();
    queue&lt;pair&lt;int, int&gt;&gt; q;
    unordered_set&lt;int&gt; seen;
    q.push({pos(0, 0), pos(1, 0)}); // tail, head
    seen.insert(encode(pos(0, 0), pos(1, 0)));
    int steps = 0;
    auto valid = [&amp;](int x, int y) {
      bool v = x &gt;= 0 &amp;&amp; x &lt; n &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; n &amp;&amp; !grid[y][x];      
      return v;
    };
    while (!q.empty()) {
      int size = q.size();
      while (size--) {
        auto p = q.front(); q.pop();
        int y0 = p.first / 100;
        int x0 = p.first % 100;
        int y1 = p.second / 100;
        int x1 = p.second % 100;
                        
        if (x0 == n - 2 &amp;&amp; y0 == n - 1 &amp;&amp;
            x1 == n - 1 &amp;&amp; y1 == n - 1) {
          return steps;
        }
        
        bool h = y0 == y1;        
        
        for (int i = 0; i &lt; 3; ++i) {
          int tx0 = x0;
          int ty0 = y0;
          int tx1 = x1;
          int ty1 = y1;
          int rx = x0;
          int ry = y0;
          switch (i) {
            case 0: // down              
              ++ty0;
              ++ty1;
              break;
            case 1: // right
              ++tx0;
              ++tx1;
              break;
            case 2: // rotate              
              ++rx;
              ++ry;
              if (h) { // clockwise 
                --tx1;
                ++ty1;
              } else { // counterclockwise  
                ++tx1;
                --ty1;
              }
              break;
          }                    
          if (!valid(tx0, ty0) || !valid(tx1, ty1) || !valid(rx, ry)) continue;          
          int key = encode(pos(tx0, ty0), pos(tx1, ty1));
          if (seen.count(key)) continue;
          seen.insert(key);
          q.push({pos(tx0, ty0), pos(tx1, ty1)});
        }
      }
      ++steps;
    }
    return -1;
  }
};</pre>
</div></div>



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



<p>dp[i][j].first = min steps to reach i,j (tail pos) facing right<br>dp[i][j].second = min steps to reach i, j (tail pos) facing down<br>ans = dp[n][n-1].first</p>



<p>Time complexity: O(n^2)<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, 16 ms, 12.1MB
class Solution {
public:
  int minimumMoves(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    constexpr int kInf = 1e9;
    const int n = grid.size();
    vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; dp(n + 1, 
                                      vector&lt;pair&lt;int, int&gt;&gt;(n + 1, {kInf, kInf}));
    dp[0][1].first = dp[1][0].first = -1;
    for (int i = 1; i &lt;= n; ++i)
      for (int j = 1; j &lt;= n; ++j) {
        bool h = false;
        bool v = false;
        if (!grid[i - 1][j - 1] &amp;&amp; j &lt; n &amp;&amp; !grid[i - 1][j]) {
          dp[i][j].first = min(dp[i - 1][j].first, dp[i][j - 1].first) + 1;
          h = true;          
        }
        if (!grid[i - 1][j - 1] &amp;&amp; i &lt; n &amp;&amp; !grid[i][j - 1]) {
          dp[i][j].second = min(dp[i - 1][j].second, dp[i][j - 1].second) + 1;
          v = true;          
        }
        if (v &amp;&amp; j &lt; n &amp;&amp; !grid[i][j])
            dp[i][j].second = min(dp[i][j].second, dp[i][j].first + 1);
        if (h &amp;&amp; i &lt; n &amp;&amp; !grid[i][j])
            dp[i][j].first = min(dp[i][j].first, dp[i][j].second + 1);        
      }      
    return dp[n][n - 1].first &gt;= kInf ? -1 : dp[n][n - 1].first;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1210-minimum-moves-to-reach-target-with-rotations/">花花酱 LeetCode 1210. Minimum Moves to Reach Target with Rotations</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/searching/leetcode-1210-minimum-moves-to-reach-target-with-rotations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Sep 2019 22:16:24 +0000</pubDate>
				<category><![CDATA[Stack]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5550</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;that consists of lower case English letters and brackets.&#160; Reverse the strings&#160;in each&#160;pair of matching parentheses, starting&#160;from the innermost one. Your result should&#160;not&#160;contain&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</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>Given a string&nbsp;<code>s</code>&nbsp;that consists of lower case English letters and brackets.&nbsp;</p>



<p>Reverse the strings&nbsp;in each&nbsp;pair of matching parentheses, starting&nbsp;from the innermost one.</p>



<p>Your result should&nbsp;<strong>not</strong>&nbsp;contain any bracket.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(abcd)"
<strong>Output:</strong> "dcba"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(u(love)i)"
<strong>Output:</strong> "iloveu"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "(ed(et(oc))el)"
<strong>Output:</strong> "leetcode"
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a(bcdefghijkl(mno)p)q"
<strong>Output:</strong> "apmnolkjihgfedcbq"
</pre>



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



<ul><li><code>0 &lt;= s.length &lt;= 2000</code></li><li><code>s</code>&nbsp;only contains lower case English characters and parentheses.</li><li>It&#8217;s guaranteed that all parentheses are balanced.</li></ul>



<h2><strong>Solution: Stack</strong></h2>



<p>Use a stack of strings to track all the active strings.<br>Iterate over the input string:<br>1. Whenever there is a &#8216;(&#8216;, push an empty string to the stack.<br>2. Whenever this is a &#8216;)&#8217;, pop the top string and append the reverse of it to the new stack top.<br>3. Otherwise, append the letter to the string on top the of stack.<br><br>Once done, the (only) string on the top of the stack is the answer.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string reverseParentheses(string s) {
    stack&lt;string&gt; st;
    st.push(&quot;&quot;);
    for (char c : s) {
      if (c == '(') st.push(&quot;&quot;);
      else if (c != ')') st.top() += c;
      else {
        string t = st.top(); st.pop();
        st.top().insert(end(st.top()), rbegin(t), rend(t));
      }
    }
    return st.top();
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/">花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses</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/stack/leetcode-1190-reverse-substrings-between-each-pair-of-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 5. Longest Palindromic Substring</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 07:45:12 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3917</guid>

					<description><![CDATA[<p>Problem Given a string&#160;s, find the longest palindromic substring in&#160;s. You may assume that the maximum length of&#160;s&#160;is 1000. Example 1: Input: "babad" Output: "bab"&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/">花花酱 LeetCode 5. Longest Palindromic Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a string&nbsp;<strong>s</strong>, find the longest palindromic substring in&nbsp;<strong>s</strong>. You may assume that the maximum length of&nbsp;<strong>s</strong>&nbsp;is 1000.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "babad"
<strong>Output:</strong> "bab"
<strong>Note:</strong> "aba" is also a valid answer.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "cbbd"
<strong>Output:</strong> "bb"
</pre>
<h1><strong>Solution: DP</strong></h1>
<p>Try all possible i and find the longest palindromic string whose center is i (odd case) and i / i + 1 (even case).</p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms, 8.7 MB
class Solution {
public:
  string longestPalindrome(string s) {
    const int n = s.length();
    auto getLen = [&amp;](int l, int r) {
      while (l &gt;= 0 &amp;&amp; r &lt; n 
             &amp;&amp; s[l] == s[r]) {
        --l;
        ++r;
      }
      return r - l - 1;
    };
    int len = 0;
    int start = 0;
    for (int i = 0; i &lt; n; ++i) {
      int cur = max(getLen(i, i), 
                    getLen(i, i + 1));
      if (cur &gt; len) {
        len = cur;
        start = i - (len - 1) / 2;
      }
    }
    return s.substr(start, len);
  }
};</pre><p></div></div></p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 6 ms， 36.5 MB
class Solution {
  public String longestPalindrome(String s) {
    int len = 0;
    int start = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      int cur = Math.max(getLen(s, i, i), 
                         getLen(s, i, i + 1));
      if (cur &gt; len) {
        len = cur;
        start = i - (cur - 1) / 2;
      }
    }
    return s.substring(start, start + len);
  }
  
  private int getLen(String s, int l, int r) {
    while (l &gt;= 0 &amp;&amp; r &lt; s.length() 
           &amp;&amp; s.charAt(l) == s.charAt(r)) {
      --l;
      ++r;
    }
    return r - l - 1;
  }
}</pre><p></div></div></p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 812 ms, 12.7MB
class Solution:
  def longestPalindrome(self, s: str) -&gt; str:
    n = len(s)
    def getLen(l, r):
      while l &gt;= 0 and r &lt; n and s[l] == s[r]:
        l -= 1
        r += 1
      return r - l - 1
    
    start = 0
    length = 0    
    for i in range(n):      
      cur = max(getLen(i, i),
                getLen(i, i + 1))
      if cur &lt;= length: continue
      length = cur
      start = i - (cur - 1) // 2
    return s[start : start + length]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/">花花酱 LeetCode 5. Longest Palindromic Substring</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/dynamic-programming/leetcode-5-longest-palindromic-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
