<?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>chess Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/chess/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/chess/</link>
	<description></description>
	<lastBuildDate>Sat, 03 Apr 2021 18:29:15 +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>chess Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/chess/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1812. Determine Color of a Chessboard Square</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1812-determine-color-of-a-chessboard-square/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1812-determine-color-of-a-chessboard-square/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Apr 2021 18:28:02 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8297</guid>

					<description><![CDATA[<p>You are given&#160;coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return&#160;true&#160;if the square&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1812-determine-color-of-a-chessboard-square/">花花酱 LeetCode 1812. Determine Color of a Chessboard Square</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&nbsp;<code>coordinates</code>, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.</p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/02/19/screenshot-2021-02-20-at-22159-pm.png" alt=""/></figure>



<p>Return&nbsp;<code>true</code><em>&nbsp;if the square is white, and&nbsp;</em><code>false</code><em>&nbsp;if the square is black</em>.</p>



<p>The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> coordinates = "a1"
<strong>Output:</strong> false
<strong>Explanation:</strong> From the chessboard above, the square with coordinates "a1" is black, so return false.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> coordinates = "h3"
<strong>Output:</strong> true
<strong>Explanation:</strong> From the chessboard above, the square with coordinates "h3" is white, so return true.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> coordinates = "c7"
<strong>Output:</strong> false
</pre>



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



<ul><li><code>coordinates.length == 2</code></li><li><code>'a' &lt;= coordinates[0] &lt;= 'h'</code></li><li><code>'1' &lt;= coordinates[1] &lt;= '8'</code></li></ul>



<h2><strong>Solution: Mod2</strong></h2>



<p>return (row_index + col_index) % 2 == 0</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  bool squareIsWhite(string coordinates) {
    return ((coordinates[0] - 'a') + (coordinates[1] - '0')) % 2 == 0;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1812-determine-color-of-a-chessboard-square/">花花酱 LeetCode 1812. Determine Color of a Chessboard Square</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/string/leetcode-1812-determine-color-of-a-chessboard-square/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1222. Queens That Can Attack the King</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1222-queens-that-can-attack-the-king/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1222-queens-that-can-attack-the-king/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 14 Oct 2019 14:48:56 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[king]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[queen]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5757</guid>

					<description><![CDATA[<p>On an&#160;8&#215;8&#160;chessboard, there can be multiple Black Queens and one White King. Given an array of integer coordinates&#160;queens&#160;that represents the positions of the Black Queens,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1222-queens-that-can-attack-the-king/">花花酱 LeetCode 1222. Queens That Can Attack the King</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>On an&nbsp;<strong>8&#215;8</strong>&nbsp;chessboard, there can be multiple Black Queens and one White King.</p>



<p>Given an array of integer coordinates&nbsp;<code>queens</code>&nbsp;that represents the positions of the Black Queens, and a pair of coordinates&nbsp;<code>king</code>&nbsp;that represent the position of the White King, return the coordinates of all the queens (in any order) that can attack the King.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0]
<strong>Output:</strong> [[0,1],[1,0],[3,3]]
<strong>Explanation:</strong>&nbsp; 
The queen at [0,1] can attack the king cause they're in the same row. 
The queen at [1,0] can attack the king cause they're in the same column. 
The queen at [3,3] can attack the king cause they're in the same diagnal. 
The queen at [0,4] can't attack the king cause it's blocked by the queen at [0,1]. 
The queen at [4,0] can't attack the king cause it's blocked by the queen at [1,0]. 
The queen at [2,4] can't attack the king cause it's not in the same row/column/diagnal as the king.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3]
<strong>Output:</strong> [[2,2],[3,4],[4,4]]
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/10/01/untitled-diagram-2.jpg" alt=""/></figure>



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



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



<ul><li><code>1 &lt;= queens.length&nbsp;&lt;= 63</code></li><li><code>queens[0].length == 2</code></li><li><code>0 &lt;= queens[i][j] &lt;&nbsp;8</code></li><li><code>king.length == 2</code></li><li><code>0 &lt;= king[0], king[1] &lt; 8</code></li><li>At most one piece is allowed in a cell.</li></ul>



<h2><strong>Solution2: Simulation</strong></h2>



<p>Time complexity: O(n)<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:
  vector&lt;vector&lt;int&gt;&gt; queensAttacktheKing(vector&lt;vector&lt;int&gt;&gt;&amp; queens, vector&lt;int&gt;&amp; king) {    
    vector&lt;vector&lt;int&gt;&gt; b(8, vector&lt;int&gt;(8));
    for (const auto&amp; q : queens)
      b[q[0]][q[1]] = 1;
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const auto&amp; q : queens) {
      for (int dx = -1; dx &lt;= 1; ++dx)
        for (int dy = -1; dy &lt;= 1; ++dy) {
          if (dx == 0 &amp;&amp; dy == 0) continue;
          int x = q[1] + dx;
          int y = q[0] + dy;
          while (x &gt;= 0 &amp;&amp; y &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &lt; 8 &amp;&amp; !b[y][x]) {
            if (x == king[1] &amp;&amp; y == king[0])
              ans.push_back(q);            
            x += dx;
            y += dy;
          }
        }
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: HashTable + Binary Search</strong></h2>



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



<p>Support arbitrarily large boards, e.g. 1e9 x 1e9 with 1e6  # of queens.</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; queensAttacktheKing(vector&lt;vector&lt;int&gt;&gt;&amp; queens, vector&lt;int&gt;&amp; king) {    
    unordered_map&lt;int, map&lt;int, vector&lt;int&gt;&gt;&gt; rows, cols, diag1, diag2;    
    for (const auto&amp; q : queens) {
      const int x = q[1];
      const int y = q[0];
      rows[y][x] = q;
      cols[x][y] = q;
      diag1[x + y][x] = q;
      diag2[x - y][x] = q;
    }
    
    const int x = king[1];
    const int y = king[0];
    vector&lt;vector&lt;int&gt;&gt; ans;
    find(rows, y, x, ans);
    find(cols, x, y, ans);
    find(diag1, x + y, x, ans);
    find(diag2, x - y, x, ans);
    return ans;
  }
private:
  void find(const unordered_map&lt;int, map&lt;int, vector&lt;int&gt;&gt;&gt;&amp; m, int idx, int key, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {    
    if (!m.count(idx)) return;
    const auto&amp; d = m.at(idx);
    auto it = d.upper_bound(key);
    if (it != end(d))
      ans.push_back(it-&gt;second);
    if (it != begin(d))
      ans.push_back(prev(it)-&gt;second);    
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1222-queens-that-can-attack-the-king/">花花酱 LeetCode 1222. Queens That Can Attack the King</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/simulation/leetcode-1222-queens-that-can-attack-the-king/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 999. Available Captures for Rook</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-999-available-captures-for-rook/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-999-available-captures-for-rook/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 Feb 2019 17:45:03 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[board]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4892</guid>

					<description><![CDATA[<p>On an 8 x 8 chessboard, there is one white rook.&#160; There also may be empty squares, white bishops, and black pawns.&#160; These are given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-999-available-captures-for-rook/">花花酱 LeetCode 999. Available Captures for Rook</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>On an 8 x 8 chessboard, there is one white rook.&nbsp; There also may be empty squares, white bishops, and black pawns.&nbsp; These are given as characters &#8216;R&#8217;, &#8216;.&#8217;, &#8216;B&#8217;, and &#8216;p&#8217; respectively. Uppercase characters represent white pieces, and lowercase characters represent black pieces.</p>



<p>The rook moves as in the rules of Chess: it chooses one of four cardinal directions (north, east, west, and south), then moves in that direction until it chooses to stop, reaches the edge of the board, or captures an opposite colored pawn by moving to the same square it occupies.&nbsp; Also, rooks cannot move into the same square as other friendly bishops.</p>



<p>Return the number of pawns the rook can capture in one move.</p>



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



<figure class="wp-block-image is-resized"><img src="https://assets.leetcode.com/uploads/2019/02/20/1253_example_1_improved.PNG" alt="" width="299" height="303"/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","R",".",".",".","p"],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
<strong>Output: </strong>3
<strong>Explanation: </strong>
In this example the rook is able to capture all the pawns.
</pre>



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



<figure class="wp-block-image is-resized"><img src="https://assets.leetcode.com/uploads/2019/02/19/1253_example_2_improved.PNG" alt="" width="298" height="304"/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[[".",".",".",".",".",".",".","."],[".","p","p","p","p","p",".","."],[".","p","p","B","p","p",".","."],[".","p","B","R","B","p",".","."],[".","p","p","B","p","p",".","."],[".","p","p","p","p","p",".","."],[".",".",".",".",".",".",".","."],[".",".",".",".",".",".",".","."]]
<strong>Output: </strong>0
<strong>Explanation: </strong>
Bishops are blocking the rook to capture any pawn.
</pre>



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



<figure class="wp-block-image is-resized"><img src="https://assets.leetcode.com/uploads/2019/02/20/1253_example_3_improved.PNG" alt="" width="294" height="299"/></figure>



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>[[".",".",".",".",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".","p",".",".",".","."],["p","p",".","R",".","p","B","."],[".",".",".",".",".",".",".","."],[".",".",".","B",".",".",".","."],[".",".",".","p",".",".",".","."],[".",".",".",".",".",".",".","."]]
<strong>Output: </strong>3
<strong>Explanation: </strong>
The rook can capture the pawns at positions b5, d6 and f5.
</pre>



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



<ol><li><code>board.length == board[i].length == 8</code></li><li><code>board[i][j]</code>&nbsp;is either&nbsp;<code>'R'</code>,&nbsp;<code>'.'</code>,&nbsp;<code>'B'</code>, or&nbsp;<code>'p'</code></li><li>There is exactly one cell with&nbsp;<code>board[i][j] == 'R'</code></li></ol>



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



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int numRookCaptures(vector&lt;vector&lt;char&gt;&gt;&amp; board) {        
    int ans = 0;
    auto check = [&amp;board](int x, int y, int dx, int dy) {
      x += dx;
      y += dy;
      while (x &gt;= 0 &amp;&amp; x &lt; 8 &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; 8) {
        if (board[y][x] == 'p') return 1;
        if (board[y][x] != '.') break;
        x += dx;
        y += dy;
      }
      return 0;
    };
    
    array&lt;int, 5&gt; dirs{1, 0, -1, 0, 1};
    for (int i = 0; i &lt; 8; ++i)
      for (int j = 0; j &lt; 8; ++j)
        if (board[i][j] == 'R')
          for (int d = 0; d &lt; 4; ++d)          
            ans += check(j, i, dirs[d], dirs[d + 1]);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-999-available-captures-for-rook/">花花酱 LeetCode 999. Available Captures for Rook</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/simulation/leetcode-999-available-captures-for-rook/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 935. Knight Dialer</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-935-knight-dialer/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-935-knight-dialer/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 04 Nov 2018 15:58:59 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[knight]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4257</guid>

					<description><![CDATA[<p>Problem https://leetcode.com/problems/knight-dialer/description/ A chess knight can move as indicated in the chess diagram below:  .            &#160; This time, we place&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-935-knight-dialer/">花花酱 LeetCode 935. Knight Dialer</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><iframe width="500" height="375" src="https://www.youtube.com/embed/HTnIFivp0aw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/knight-dialer/description/">https://leetcode.com/problems/knight-dialer/description/</a></p>
<p>A chess knight can move as indicated in the chess diagram below:</p>
<p><img src="https://assets.leetcode.com/uploads/2018/10/12/knight.png" alt="" /> .           <img src="https://assets.leetcode.com/uploads/2018/10/30/keypad.png" alt="" /></p>
<p>&nbsp;</p>
<p>This time, we place our chess knight on any numbered key of a phone pad (indicated above), and the knight makes <code>N-1</code> hops.  Each hop must be from one key to another numbered key.</p>
<p>Each time it lands on a key (including the initial placement of the knight), it presses the number of that key, pressing <code>N</code> digits total.</p>
<p>How many distinct numbers can you dial in this manner?</p>
<p>Since the answer may be large, <strong>output the answer modulo <code>10^9 + 7</code></strong>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">1</span>
<strong>Output: </strong><span id="example-output-1">10</span>
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">2</span>
<strong>Output: </strong><span id="example-output-2">20</span>
</pre>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">3</span>
<strong>Output: </strong><span id="example-output-3">46</span>
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= N &lt;= 5000</code></li>
</ul>
<h1><img class="alignnone size-full wp-image-4265" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/11/935-ep229.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/11/935-ep229.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/11/935-ep229-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/11/935-ep229-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution: DP</strong></h1>
<h2>V1</h2>
<p>Similar to <a href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</a></p>
<p>We can define dp[k][i][j] as # of ways to dial and the last key is (j, i) after k steps</p>
<p>Note: dp[*][3][0], dp[*][3][2] are always zero for all the steps.</p>
<p>Init: dp[0][i][j] = 1</p>
<p>Transition: dp[k][i][j] = sum(dp[k &#8211; 1][i + dy][j + dx]) 8 ways of move from last step.</p>
<p>ans = sum(dp[k])</p>
<p>Time complexity: O(kmn) or O(k * 12 * 8) = O(k)</p>
<p>Space complexity: O(kmn) -&gt; O(mn) or O(12*8) = O(1)</p>
<h2>V2</h2>
<p>define dp[k][i] as # of ways to dial and the last key is i after k steps</p>
<p>init: dp[0][0:10] = 1</p>
<p>transition: dp[k][i] = sum(dp[k-1][j]) that j can move to i</p>
<p>ans: sum(dp[k])</p>
<p>Time complexity: O(k * 10) = O(k)</p>
<p>Space complexity: O(k * 10) -&gt; O(10) = O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++ V1</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 96 ms
class Solution {
public:
  int knightDialer(int N) {
    constexpr int kMod = 1e9 + 7;
    int dirs[8][2] = {{-2, -1}, {-2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {2, -1}, {2, 1}};
    vector&lt;vector&lt;int&gt;&gt; dp(4, vector&lt;int&gt;(3, 1));
    dp[3][0] = dp[3][2] = 0;    
    for (int k = 1; k &lt; N; ++k) {
      vector&lt;vector&lt;int&gt;&gt; tmp(4, vector&lt;int&gt;(3));
      for (int i = 0; i &lt; 4; ++i)
        for (int j = 0; j &lt; 3; ++j) {
          if (i == 3 &amp;&amp; j != 1) continue;
          for (int d = 0; d &lt; 8; ++d) {           
            int tx = j + dirs[d][0];
            int ty = i + dirs[d][1];
            if (tx &lt; 0 || ty &lt; 0 || tx &gt;= 3 || ty &gt;= 4) continue;
            tmp[i][j] = (tmp[i][j] + dp[ty][tx]) % kMod;
          }          
        }
      dp.swap(tmp);
    }
    int ans = 0;
    for (int i = 0; i &lt; 4; ++i)
      for (int j = 0; j &lt; 3; ++j)
        ans = (ans + dp[i][j]) % kMod;
    return ans;
  }
};</pre><p></div><h2 class="tabtitle">C++ V2</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 24 ms
public:
  int knightDialer(int N) {
    constexpr int kMod = 1e9 + 7;
    vector&lt;vector&lt;int&gt;&gt; moves{{4,6},{8,6},{7,9},{4,8},{3,9,0},{},{1,7,0},{2,6},{1,3},{2,4}};
    vector&lt;int&gt; dp(10, 1);
    for (int k = 1; k &lt; N; ++k) {
      vector&lt;int&gt; tmp(10);
      for (int i = 0; i &lt; 10; ++i)
        for (int nxt : moves[i])
          tmp[nxt] = (tmp[nxt] + dp[i]) % kMod;        
      dp.swap(tmp);
    }
    int ans = 0;
    for (int i = 0; i &lt; 10; ++i)
      ans = (ans + dp[i]) % kMod;
    return ans;
  }
};</pre><p></div></div></p>
<h1><strong>Related Problem</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</a></li>
<li><a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-576-out-of-boundary-paths/">花花酱 LeetCode 576. Out of Boundary Paths</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-935-knight-dialer/">花花酱 LeetCode 935. Knight Dialer</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-935-knight-dialer/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 688. Knight Probability in Chessboard</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 02 Oct 2017 06:18:42 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[chess]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[knight]]></category>
		<category><![CDATA[probability]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=515</guid>

					<description><![CDATA[<p>https://leetcode.com/problems/knight-probability-in-chessboard/description/ Problem: On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly Kmoves. The rows and columns are 0 indexed, so&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</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><iframe width="500" height="375" src="https://www.youtube.com/embed/MyJvMydR2G4?feature=oembed" frameborder="0" gesture="media" allowfullscreen></iframe></p>
<p><a href="https://leetcode.com/problems/knight-probability-in-chessboard/description/">https://leetcode.com/problems/knight-probability-in-chessboard/description/</a></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>On an <code>N</code>x<code>N</code> chessboard, a knight starts at the <code>r</code>-th row and <code>c</code>-th column and attempts to make exactly <code>K</code>moves. The rows and columns are 0 indexed, so the top-left square is <code>(0, 0)</code>, and the bottom-right square is <code>(N-1, N-1)</code>.</p>
<p>A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.</p>
<p><img src="https://leetcode.com/static/images/problemset/knight.png" />Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.</p>
<p>The knight continues moving until it has made exactly <code>K</code> moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Input: 3, 2, 0, 0
Output: 0.0625
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on 
the board. The total probability the knight stays on the board is 0.0625.</pre><p><b>Note:</b></p>
<ul>
<li><code>N</code> will be between 1 and 25.</li>
<li><code>K</code> will be between 0 and 100.</li>
<li>The knight always initially starts on the board.</li>
</ul>
</div>
<div></div>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<div id="interviewed-div"><strong>Idea:</strong></div>
<div>Dynamic programming</div>
<div>Count the ways to reach (x, y) after k moves from start.</div>
<div></div>
<div></div>
<div><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png"><img class="alignnone size-full wp-image-522" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/688-ep79-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></div>
<div></div>
<div></div>
<div></div>
<div><strong>Time Complexity: </strong>O(k*n^2)</div>
<div></div>
<div><strong>Space Complexity: </strong>O(n^2)</div>
<div></div>
<div><strong>Solution:</strong></div>
<div>
<pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    double knightProbability(int N, int K, int r, int c) {
        vector&lt;vector&lt;double&gt;&gt; dp0(N, vector&lt;double&gt;(N, 0.0));
        dp0[r][c] = 1.0;
        int dirs[8][2] = {{1, 2}, {-1, -2}, {1, -2}, {-1, 2},
                          {2, 1}, {-2, -1}, {2, -1}, {-2, 1}};
        for (int k = 0; k &lt; K; ++k) {            
            vector&lt;vector&lt;double&gt;&gt; dp1(N, vector&lt;double&gt;(N, 0.0));
            for (int i = 0; i &lt; N; ++i)
                for (int j = 0; j &lt; N; ++j) 
                    for (int m = 0; m &lt; 8; ++m) {
                        int x = j + dirs[m][0];
                        int y = i + dirs[m][1];
                        if (x &lt; 0 || y &lt; 0 || x &gt;= N || y &gt;= N) continue;
                        dp1[i][j] += dp0[y][x];
                    }
            std::swap(dp0, dp1);
        }
        
        double total = 0;
        for (int i = 0; i &lt; N; ++i)
            for (int j = 0; j &lt; N; ++j)
                total += dp0[i][j];
        
        return total / pow(8, K);
    }
};</pre>
</div>
<p>&nbsp;</p>
<p><strong>Related problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-62-unique-paths/">[解题报告] LeetCode 62. Unique Paths</a></li>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-63-unique-paths-ii/">[解题报告] LeetCode 63. Unique Paths II</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/688-knight-probability-in-chessboard/">花花酱 688. Knight Probability in Chessboard</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/688-knight-probability-in-chessboard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
