<?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>matrix Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/matrix/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/matrix/</link>
	<description></description>
	<lastBuildDate>Sun, 30 Apr 2023 16:55:20 +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>matrix Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/matrix/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2661. First Completely Painted Row or Column</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 16:52:12 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10039</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;arr, and an&#160;m x n&#160;integer&#160;matrix&#160;mat.&#160;arr&#160;and&#160;mat&#160;both contain&#160;all&#160;the integers in the range&#160;[1, m * n]. Go through each index&#160;i&#160;in&#160;arr&#160;starting from index&#160;0&#160;and paint the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/">花花酱 LeetCode 2661. First Completely Painted Row or Column</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>arr</code>, and an&nbsp;<code>m x n</code>&nbsp;integer&nbsp;<strong>matrix</strong>&nbsp;<code>mat</code>.&nbsp;<code>arr</code>&nbsp;and&nbsp;<code>mat</code>&nbsp;both contain&nbsp;<strong>all</strong>&nbsp;the integers in the range&nbsp;<code>[1, m * n]</code>.</p>



<p>Go through each index&nbsp;<code>i</code>&nbsp;in&nbsp;<code>arr</code>&nbsp;starting from index&nbsp;<code>0</code>&nbsp;and paint the cell in&nbsp;<code>mat</code>&nbsp;containing the integer&nbsp;<code>arr[i]</code>.</p>



<p>Return&nbsp;<em>the smallest index</em>&nbsp;<code>i</code>&nbsp;<em>at which either a row or a column will be completely painted in</em>&nbsp;<code>mat</code>.</p>



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



<figure class="wp-block-image"><img src="https://leetcode.com/problems/first-completely-painted-row-or-column/description/image%20explanation%20for%20example%201" alt=""/></figure>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2023/01/18/grid1.jpg" alt="image explanation for example 1"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,3,4,2], mat = [[1,4],[2,3]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The moves are shown in order, and both the first row and second column of the matrix become fully painted at arr[2].
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2023/01/18/grid2.jpg" alt="image explanation for example 2"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,8,7,4,1,3,5,6,9], mat = [[3,2,5],[1,4,6],[8,7,9]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The second column becomes fully painted at arr[3].
</pre>



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



<ul><li><code>m == mat.length</code></li><li><code>n = mat[i].length</code></li><li><code>arr.length == m * n</code></li><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arr[i], mat[r][c] &lt;= m * n</code></li><li>All the integers of&nbsp;<code>arr</code>&nbsp;are&nbsp;<strong>unique</strong>.</li><li>All the integers of&nbsp;<code>mat</code>&nbsp;are&nbsp;<strong>unique</strong>.</li></ul>



<h2><strong>Solution: Map + Counter</strong></h2>



<p>Use a map to store the position of each integer.</p>



<p>Use row counters and column counters to track how many elements have been painted.</p>



<p>Time complexity: O(m*n + m + n)<br>Space complexity: O(m*n + m + n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int firstCompleteIndex(vector&lt;int&gt;&amp; arr, vector&lt;vector&lt;int&gt;&gt;&amp; mat) {
    const int m = mat.size();
    const int n = mat[0].size();
    vector&lt;int&gt; rows(m);
    vector&lt;int&gt; cols(n);
    vector&lt;pair&lt;int, int&gt;&gt; pos(m * n + 1);
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        pos[mat[i][j]] = {i, j};
    
    for (int i = 0; i &lt; arr.size(); ++i) {
      auto [r, c] = pos[arr[i]];
      if (++rows[r] == n) return i;
      if (++cols[c] == m) return i;
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2661-first-completely-painted-row-or-column/">花花酱 LeetCode 2661. First Completely Painted Row or Column</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/hashtable/leetcode-2661-first-completely-painted-row-or-column/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2639. Find the Width of Columns of a Grid</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Apr 2023 15:22:36 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[length]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[width]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10006</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;m x n&#160;integer matrix&#160;grid. The width of a column is the maximum&#160;length&#160;of its integers. For example, if&#160;grid = [[-10], [3], [12]], the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/">花花酱 LeetCode 2639. Find the Width of Columns of a Grid</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 a&nbsp;<strong>0-indexed</strong>&nbsp;<code>m x n</code>&nbsp;integer matrix&nbsp;<code>grid</code>. The width of a column is the maximum&nbsp;<strong>length&nbsp;</strong>of its integers.</p>



<ul><li>For example, if&nbsp;<code>grid = [[-10], [3], [12]]</code>, the width of the only column is&nbsp;<code>3</code>&nbsp;since&nbsp;<code>-10</code>&nbsp;is of length&nbsp;<code>3</code>.</li></ul>



<p>Return&nbsp;<em>an integer array</em>&nbsp;<code>ans</code>&nbsp;<em>of size</em>&nbsp;<code>n</code>&nbsp;<em>where</em>&nbsp;<code>ans[i]</code>&nbsp;<em>is the width of the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>column</em>.</p>



<p>The&nbsp;<strong>length</strong>&nbsp;of an integer&nbsp;<code>x</code>&nbsp;with&nbsp;<code>len</code>&nbsp;digits is equal to&nbsp;<code>len</code>&nbsp;if&nbsp;<code>x</code>&nbsp;is non-negative, and&nbsp;<code>len + 1</code>&nbsp;otherwise.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1],[22],[333]]
<strong>Output:</strong> [3]
<strong>Explanation:</strong> In the 0<sup>th</sup> column, 333 is of length 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[-15,1,3],[15,7,12],[5,6,-2]]
<strong>Output:</strong> [3,1,2]
<strong>Explanation:</strong> 
In the 0<sup>th</sup> column, only -15 is of length 3.
In the 1<sup>st</sup> column, all integers are of length 1. 
In the 2<sup>nd</sup> column, both 12 and -2 are of length 2.
</pre>



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



<ul><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 100</code></li><li><code>-10<sup>9</sup> &lt;= grid[r][c] &lt;= 10<sup>9</sup></code></li></ul>



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



<p>Note: width of &#8216;0&#8217; is 1.</p>



<p>Time complexity: O(m*n*log(x))<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;int&gt; findColumnWidth(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    vector&lt;int&gt; ans;
    for (int j = 0; j &lt; grid[0].size(); ++j) {
      int maxWidth = 1;
      for (int i = 0; i &lt; grid.size(); ++i) {
        int x = grid[i][j];
        int width = 0;        
        if (x &lt; 0) {
          x = -x;
          ++width;
        }
        while (x) {
          x /= 10;
          ++width;
        }        
        maxWidth = max(maxWidth, width);
      }
      ans.push_back(maxWidth);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-2639-find-the-width-of-columns-of-a-grid/">花花酱 LeetCode 2639. Find the Width of Columns of a Grid</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-2639-find-the-width-of-columns-of-a-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2643. Row With Maximum Ones</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2643-row-with-maximum-ones/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2643-row-with-maximum-ones/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Apr 2023 01:28:50 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9999</guid>

					<description><![CDATA[<p>Given a&#160;m x n&#160;binary matrix&#160;mat, find the&#160;0-indexed&#160;position of the row that contains the&#160;maximum&#160;count of&#160;ones,&#160;and the number of ones in that row. In case there are&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2643-row-with-maximum-ones/">花花酱 LeetCode 2643. Row With Maximum Ones</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&nbsp;<code>m x n</code>&nbsp;binary matrix&nbsp;<code>mat</code>, find the&nbsp;<strong>0-indexed</strong>&nbsp;position of the row that contains the&nbsp;<strong>maximum</strong>&nbsp;count of&nbsp;<strong>ones,</strong>&nbsp;and the number of ones in that row.</p>



<p>In case there are multiple rows that have the maximum count of ones, the row with the&nbsp;<strong>smallest row number</strong>&nbsp;should be selected.</p>



<p>Return<em>&nbsp;an array containing the index of the row, and the number of ones in it.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,1],[1,0]]
<strong>Output:</strong> [0,1]
<strong>Explanation:</strong> Both rows have the same number of 1's. So we return the index of the smaller row, 0, and the maximum count of ones (1<code>)</code>. So, the answer is [0,1]. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,0,0],[0,1,1]]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> The row indexed 1 has the maximum count of ones <code>(2)</code>. So we return its index, <code>1</code>, and the count. So, the answer is [1,2].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,0],[1,1],[0,0]]
<strong>Output:</strong> [1,2]
<strong>Explanation:</strong> The row indexed 1 has the maximum count of ones (2). So the answer is [1,2].
</pre>



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



<ul><li><code>m == mat.length</code>&nbsp;</li><li><code>n == mat[i].length</code>&nbsp;</li><li><code>1 &lt;= m, n &lt;= 100</code>&nbsp;</li><li><code>mat[i][j]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Counting</strong></h2>



<p>Time complexity: O(m*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;int&gt; rowAndMaximumOnes(vector&lt;vector&lt;int&gt;&gt;&amp; mat) {
    vector&lt;int&gt; ans(2);
    for (int i = 0; i &lt; mat.size(); ++i) {
      int ones = accumulate(begin(mat[i]), end(mat[i]), 0);
      if (ones &gt; ans[1]) {
        ans[0] = i;
        ans[1] = ones;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2643-row-with-maximum-ones/">花花酱 LeetCode 2643. Row With Maximum Ones</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-2643-row-with-maximum-ones/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2373. Largest Local Values in a Matrix</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-2373-largest-local-values-in-a-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-2373-largest-local-values-in-a-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Aug 2022 04:18:53 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9783</guid>

					<description><![CDATA[<p>You are given an&#160;n x n&#160;integer matrix&#160;grid. Generate an integer matrix&#160;maxLocal&#160;of size&#160;(n - 2) x (n - 2)&#160;such that: maxLocal[i][j]&#160;is equal to the&#160;largest&#160;value of the&#160;3&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2373-largest-local-values-in-a-matrix/">花花酱 LeetCode 2373. Largest Local Values in a Matrix</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;<code>n x n</code>&nbsp;integer matrix&nbsp;<code>grid</code>.</p>



<p>Generate an integer matrix&nbsp;<code>maxLocal</code>&nbsp;of size&nbsp;<code>(n - 2) x (n - 2)</code>&nbsp;such that:</p>



<ul><li><code>maxLocal[i][j]</code>&nbsp;is equal to the&nbsp;<strong>largest</strong>&nbsp;value of the&nbsp;<code>3 x 3</code>&nbsp;matrix in&nbsp;<code>grid</code>&nbsp;centered around row&nbsp;<code>i + 1</code>&nbsp;and column&nbsp;<code>j + 1</code>.</li></ul>



<p>In other words, we want to find the largest value in every contiguous&nbsp;<code>3 x 3</code>&nbsp;matrix in&nbsp;<code>grid</code>.</p>



<p>Return&nbsp;<em>the generated matrix</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/06/21/ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]]
<strong>Output:</strong> [[9,9],[8,6]]
<strong>Explanation:</strong> The diagram above shows the original matrix and the generated matrix.
Notice that each value in the generated matrix corresponds to the largest value of a contiguous 3 x 3 matrix in grid.</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/07/02/ex2new2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,1,1,1,1],[1,1,1,1,1],[1,1,2,1,1],[1,1,1,1,1],[1,1,1,1,1]]
<strong>Output:</strong> [[2,2,2],[2,2,2],[2,2,2]]
<strong>Explanation:</strong> Notice that the 2 is contained within every contiguous 3 x 3 matrix in grid.
</pre>



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



<ul><li><code>n == grid.length == grid[i].length</code></li><li><code>3 &lt;= n &lt;= 100</code></li><li><code>1 &lt;= grid[i][j] &lt;= 100</code></li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>Time complexity: O(n*n*9)<br>Space complexity: O(n*n)</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; largestLocal(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {    
    const int m = grid.size() - 2;
    vector&lt;vector&lt;int&gt;&gt; ans(m, vector&lt;int&gt;(m));
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; m; ++j)        
        for (int dy = 0; dy &lt;= 2; ++dy)
          for (int dx = 0; dx &lt;= 2; ++dx)
            ans[i][j] = max(ans[i][j], grid[i + dy][j + dx]);        
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2373-largest-local-values-in-a-matrix/">花花酱 LeetCode 2373. Largest Local Values in a Matrix</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/math/leetcode-2373-largest-local-values-in-a-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2125. Number of Laser Beams in a Bank</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-2125-number-of-laser-beams-in-a-bank/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-2125-number-of-laser-beams-in-a-bank/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Jan 2022 08:22:50 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9398</guid>

					<description><![CDATA[<p>Anti-theft security devices are activated inside a bank. You are given a&#160;0-indexed&#160;binary string array&#160;bank&#160;representing the floor plan of the bank, which is an&#160;m x n&#160;2D&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2125-number-of-laser-beams-in-a-bank/">花花酱 LeetCode 2125. Number of Laser Beams in a Bank</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>Anti-theft security devices are activated inside a bank. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;binary string array&nbsp;<code>bank</code>&nbsp;representing the floor plan of the bank, which is an&nbsp;<code>m x n</code>&nbsp;2D matrix.&nbsp;<code>bank[i]</code>&nbsp;represents the&nbsp;<code>i<sup>th</sup></code>&nbsp;row, consisting of&nbsp;<code>'0'</code>s and&nbsp;<code>'1'</code>s.&nbsp;<code>'0'</code>&nbsp;means the cell is empty, while<code>'1'</code>&nbsp;means the cell has a security device.</p>



<p>There is&nbsp;<strong>one</strong>&nbsp;laser beam between any&nbsp;<strong>two</strong>&nbsp;security devices&nbsp;<strong>if both</strong>&nbsp;conditions are met:</p>



<ul><li>The two devices are located on two&nbsp;<strong>different rows</strong>:&nbsp;<code>r<sub>1</sub></code>&nbsp;and&nbsp;<code>r<sub>2</sub></code>, where&nbsp;<code>r<sub>1</sub>&nbsp;&lt; r<sub>2</sub></code>.</li><li>For&nbsp;<strong>each</strong>&nbsp;row&nbsp;<code>i</code>&nbsp;where&nbsp;<code>r<sub>1</sub>&nbsp;&lt; i &lt; r<sub>2</sub></code>, there are&nbsp;<strong>no security devices</strong>&nbsp;in the&nbsp;<code>i<sup>th</sup></code>&nbsp;row.</li></ul>



<p>Laser beams are independent, i.e., one beam does not interfere nor join with another.</p>



<p>Return&nbsp;<em>the total number of laser beams in the bank</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/24/laser1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> bank = ["011001","000000","010100","001000"]
<strong>Output:</strong> 8
<strong>Explanation:</strong> Between each of the following device pairs, there is one beam. In total, there are 8 beams:
 * bank[0][1] -- bank[2][1]
 * bank[0][1] -- bank[2][3]
 * bank[0][2] -- bank[2][1]
 * bank[0][2] -- bank[2][3]
 * bank[0][5] -- bank[2][1]
 * bank[0][5] -- bank[2][3]
 * bank[2][1] -- bank[3][2]
 * bank[2][3] -- bank[3][2]
Note that there is no beam between any device on the 0<sup>th</sup> row with any on the 3<sup>rd</sup> row.
This is because the 2<sup>nd</sup> row contains security devices, which breaks the second condition.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/24/laser2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> bank = ["000","111","000"]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There does not exist two devices located on two different rows.
</pre>



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



<ul><li><code>m == bank.length</code></li><li><code>n == bank[i].length</code></li><li><code>1 &lt;= m, n &lt;= 500</code></li><li><code>bank[i][j]</code>&nbsp;is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code>.</li></ul>



<h2><strong>Solution: Rule of product</strong></h2>



<p>Just need to remember the # of devices of prev non-empty row.<br># of beams between two non-empty row equals to row[i] * row[j]<br>ans += prev * curr</p>



<p>Time complexity: O(m*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:
  int numberOfBeams(vector&lt;string&gt;&amp; bank) {    
    int ans = 0;
    int prev = 0;
    for (const string&amp; row : bank)    
      if (int curr = count(begin(row), end(row), '1')) {
        ans += prev * curr;
        prev = curr;
      }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def numberOfBeams(self, bank: List[str]) -&gt; int:
    ans = prev = 0
    for row in bank:
      if curr := row.count('1'):
        ans += prev * curr
        prev = curr
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-2125-number-of-laser-beams-in-a-bank/">花花酱 LeetCode 2125. Number of Laser Beams in a Bank</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/math/leetcode-2125-number-of-laser-beams-in-a-bank/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1975. Maximum Matrix Sum</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1975-maximum-matrix-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1975-maximum-matrix-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 23:04:43 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[flip]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[negatives]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9350</guid>

					<description><![CDATA[<p>You are given an&#160;n x n&#160;integer&#160;matrix. You can do the following operation&#160;any&#160;number of times: Choose any two&#160;adjacent&#160;elements of&#160;matrix&#160;and&#160;multiply&#160;each of them by&#160;-1. Two elements are considered&#160;adjacent&#160;if&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1975-maximum-matrix-sum/">花花酱 LeetCode 1975. Maximum Matrix Sum</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;<code>n x n</code>&nbsp;integer&nbsp;<code>matrix</code>. You can do the following operation&nbsp;<strong>any</strong>&nbsp;number of times:</p>



<ul><li>Choose any two&nbsp;<strong>adjacent</strong>&nbsp;elements of&nbsp;<code>matrix</code>&nbsp;and&nbsp;<strong>multiply</strong>&nbsp;each of them by&nbsp;<code>-1</code>.</li></ul>



<p>Two elements are considered&nbsp;<strong>adjacent</strong>&nbsp;if and only if they share a&nbsp;<strong>border</strong>.</p>



<p>Your goal is to&nbsp;<strong>maximize</strong>&nbsp;the summation of the matrix&#8217;s elements. Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;sum of the matrix&#8217;s elements using the operation mentioned above.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,-1],[-1,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> We can follow the following steps to reach sum equals 4:
- Multiply the 2 elements in the first row by -1.
- Multiply the 2 elements in the first column by -1.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/07/16/pc79-q2ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,2,3],[-1,-2,-3],[1,2,3]]
<strong>Output:</strong> 16
<strong>Explanation:</strong> We can follow the following step to reach sum equals 16:
- Multiply the 2 last elements in the second row by -1.
</pre>



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



<ul><li><code>n == matrix.length == matrix[i].length</code></li><li><code>2 &lt;= n &lt;= 250</code></li><li><code>-10<sup>5</sup>&nbsp;&lt;= matrix[i][j] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Math</strong></h2>



<p>Count the number of negative numbers. <br>1. Even negatives, we can always flip all the negatives to positives. ans = sum(abs(matrix)). <br>2. Odd negatives, there will be one negative left, we found the smallest abs(element) and let it become negative. ans = sum(abs(matrix))) &#8211; 2 * min(abs(matrix))</p>



<p>Time complexity: O(n<sup>2</sup>)<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:
  long long maxMatrixSum(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int n = matrix.size();
    long long ans = 0;
    int count = 0;
    int lo = INT_MAX;
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; n; ++j) {
        ans += abs(matrix[i][j]);
        lo = min(lo, abs(matrix[i][j]));
        count += matrix[i][j] &lt; 0;          
      }    
    return ans - (count &amp; 1) * 2 * lo;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1975-maximum-matrix-sum/">花花酱 LeetCode 1975. Maximum Matrix Sum</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/math/leetcode-1975-maximum-matrix-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 835. Image Overlap</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-835-image-overlap/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-835-image-overlap/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 23 Dec 2021 20:45:49 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9204</guid>

					<description><![CDATA[<p>You are given two images,&#160;img1&#160;and&#160;img2, represented as binary, square matrices of size&#160;n x n. A binary matrix has only&#160;0s and&#160;1s as values. We&#160;translate&#160;one image however&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-835-image-overlap/">花花酱 LeetCode 835. Image Overlap</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 two images,&nbsp;<code>img1</code>&nbsp;and&nbsp;<code>img2</code>, represented as binary, square matrices of size&nbsp;<code>n x n</code>. A binary matrix has only&nbsp;<code>0</code>s and&nbsp;<code>1</code>s as values.</p>



<p>We&nbsp;<strong>translate</strong>&nbsp;one image however we choose by sliding all the&nbsp;<code>1</code>&nbsp;bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the&nbsp;<strong>overlap</strong>&nbsp;by counting the number of positions that have a&nbsp;<code>1</code>&nbsp;in&nbsp;<strong>both</strong>&nbsp;images.</p>



<p>Note also that a translation does&nbsp;<strong>not</strong>&nbsp;include any kind of rotation. Any&nbsp;<code>1</code>&nbsp;bits that are translated outside of the matrix borders are erased.</p>



<p>Return&nbsp;<em>the largest possible overlap</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/09/overlap1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> img1 = [[1,1,0],[0,1,0],[0,1,0]], img2 = [[0,0,0],[0,1,1],[0,0,1]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We translate img1 to right by 1 unit and down by 1 unit.
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/09/overlap_step1.jpg">
The number of positions that have a 1 in both images is 3 (shown in red).
<img alt="" src="https://assets.leetcode.com/uploads/2020/09/09/overlap_step2.jpg">
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> img1 = [[1]], img2 = [[1]]
<strong>Output:</strong> 1
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> img1 = [[0]], img2 = [[0]]
<strong>Output:</strong> 0
</pre>



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



<ul><li><code>n == img1.length == img1[i].length</code></li><li><code>n == img2.length == img2[i].length</code></li><li><code>1 &lt;= n &lt;= 30</code></li><li><code>img1[i][j]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li><li><code>img2[i][j]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Hashtable of offsets</strong></h2>



<p>Enumerate all pairs of 1 cells (x1, y1) (x2, y2), the key / offset will be ((x1-x2), (y1-y2)), i.e how should we shift the image to have those two cells overlapped. Use a counter to find the most common/best offset.</p>



<p>Time complexity: O(n<sup>4</sup>) Note: this is the same as brute force / simulation method if the matrix is dense.<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 largestOverlap(vector&lt;vector&lt;int&gt;&gt;&amp; img1, vector&lt;vector&lt;int&gt;&gt;&amp; img2) {
    const int n = img1.size();
    unordered_map&lt;int, int&gt; m;
    for (int y1 = 0; y1 &lt; n; ++y1)
      for (int x1 = 0; x1 &lt; n; ++x1)
        if (img1[y1][x1])
          for (int y2 = 0; y2 &lt; n; ++y2) 
            for (int x2 = 0; x2 &lt; n; ++x2)
              if (img2[y2][x2])                 
                ++m[(x1 - x2) * 100 + (y1 - y2)];
    int ans = 0;
    for (const auto [key, count] : m)
      ans = max(ans, count);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-835-image-overlap/">花花酱 LeetCode 835. Image Overlap</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/hashtable/leetcode-835-image-overlap/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2022. Convert 1D Array Into 2D Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2022-convert-1d-array-into-2d-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2022-convert-1d-array-into-2d-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 Oct 2021 03:34:07 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[row major]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8633</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;1-dimensional (1D) integer array&#160;original, and two integers,&#160;m&#160;and&#160;n. You are tasked with creating a 2-dimensional (2D) array with&#160;m&#160;rows and&#160;n&#160;columns using&#160;all&#160;the elements from&#160;original. The&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2022-convert-1d-array-into-2d-array/">花花酱 LeetCode 2022. Convert 1D Array Into 2D Array</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 a&nbsp;<strong>0-indexed</strong>&nbsp;1-dimensional (1D) integer array&nbsp;<code>original</code>, and two integers,&nbsp;<code>m</code>&nbsp;and&nbsp;<code>n</code>. You are tasked with creating a 2-dimensional (2D) array with&nbsp;<code>m</code>&nbsp;rows and&nbsp;<code>n</code>&nbsp;columns using&nbsp;<strong>all</strong>&nbsp;the elements from&nbsp;<code>original</code>.</p>



<p>The elements from indices&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;(<strong>inclusive</strong>) of&nbsp;<code>original</code>&nbsp;should form the first row of the constructed 2D array, the elements from indices&nbsp;<code>n</code>&nbsp;to&nbsp;<code>2 * n - 1</code>&nbsp;(<strong>inclusive</strong>) should form the second row of the constructed 2D array, and so on.</p>



<p>Return&nbsp;<em>an&nbsp;</em><code>m x n</code><em>&nbsp;2D array constructed according to the above procedure, or an empty 2D array if it is impossible</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/08/26/image-20210826114243-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> original = [1,2,3,4], m = 2, n = 2
<strong>Output:</strong> [[1,2],[3,4]]
<strong>Explanation:
</strong>The constructed 2D array should contain 2 rows and 2 columns.
The first group of n=2 elements in original, [1,2], becomes the first row in the constructed 2D array.
The second group of n=2 elements in original, [3,4], becomes the second row in the constructed 2D array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> original = [1,2,3], m = 1, n = 3
<strong>Output:</strong> [[1,2,3]]
<strong>Explanation:</strong>
The constructed 2D array should contain 1 row and 3 columns.
Put all three elements in original into the first row of the constructed 2D array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> original = [1,2], m = 1, n = 1
<strong>Output:</strong> []
<strong>Explanation:
</strong>There are 2 elements in original.
It is impossible to fit 2 elements in a 1x1 2D array, so return an empty 2D array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> original = [3], m = 1, n = 2
<strong>Output:</strong> []
<strong>Explanation:</strong>
There is 1 element in original.
It is impossible to make 1 element fill all the spots in a 1x2 2D array, so return an empty 2D array.
</pre>



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



<ul><li><code>1 &lt;= original.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>1 &lt;= original[i] &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m, n &lt;= 4 * 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Brute Force</strong></h2>



<p>the i-th element in original array will have index (i//n, i % n) in the 2D array.</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; construct2DArray(vector&lt;int&gt;&amp; original, int m, int n) {
    if (original.size() != m * n) return {};
    vector&lt;vector&lt;int&gt;&gt; ans(m, vector&lt;int&gt;(n));
    for (int i = 0; i &lt; m * n; ++i)
      ans[i / n][i % n] = original[i];
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2022-convert-1d-array-into-2d-array/">花花酱 LeetCode 2022. Convert 1D Array Into 2D Array</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-2022-convert-1d-array-into-2d-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1886-determine-whether-matrix-can-be-obtained-by-rotation/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1886-determine-whether-matrix-can-be-obtained-by-rotation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Aug 2021 03:22:13 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[inplace]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[rotation]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8537</guid>

					<description><![CDATA[<p>Given two&#160;n x n&#160;binary matrices&#160;mat&#160;and&#160;target, return&#160;true&#160;if it is possible to make&#160;mat&#160;equal to&#160;target&#160;by&#160;rotating&#160;mat&#160;in&#160;90-degree increments, or&#160;false&#160;otherwise. Example 1: Input: mat = [[0,1],[1,0]], target = [[1,0],[0,1]] Output: true&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1886-determine-whether-matrix-can-be-obtained-by-rotation/">花花酱 LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation</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 two&nbsp;<code>n x n</code>&nbsp;binary matrices&nbsp;<code>mat</code>&nbsp;and&nbsp;<code>target</code>, return&nbsp;<code>true</code><em>&nbsp;if it is possible to make&nbsp;</em><code>mat</code><em>&nbsp;equal to&nbsp;</em><code>target</code><em>&nbsp;by&nbsp;<strong>rotating</strong>&nbsp;</em><code>mat</code><em>&nbsp;in&nbsp;<strong>90-degree increments</strong>, or&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/05/20/grid3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,1],[1,0]], target = [[1,0],[0,1]]
<strong>Output:</strong> true
<strong>Explanation: </strong>We can rotate mat 90 degrees clockwise to make mat equal target.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/05/20/grid4.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,1],[1,1]], target = [[1,0],[0,1]]
<strong>Output:</strong> false
<strong>Explanation:</strong> It is impossible to make mat equal to target by rotating mat.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/05/26/grid4.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[0,0,0],[0,1,0],[1,1,1]], target = [[1,1,1],[0,1,0],[0,0,0]]
<strong>Output:</strong> true
<strong>Explanation: </strong>We can rotate mat 90 degrees clockwise two times to make mat equal target.
</pre>



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



<ul><li><code>n == mat.length == target.length</code></li><li><code>n == mat[i].length == target[i].length</code></li><li><code>1 &lt;= n &lt;= 10</code></li><li><code>mat[i][j]</code>&nbsp;and&nbsp;<code>target[i][j]</code>&nbsp;are either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



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



<p>Time complexity: O(n<sup>2</sup>)<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:
  bool findRotation(vector&lt;vector&lt;int&gt;&gt;&amp; mat, vector&lt;vector&lt;int&gt;&gt;&amp; target) {    
    const int n = mat.size();
    auto rot = [n](vector&lt;vector&lt;int&gt;&gt;&amp; mat) {      
      for (int i = 0; i &lt; n; ++i)
        for (int j = i; j &lt; n; ++j)
          swap(mat[i][j], mat[j][i]);
      for (int j = 0; j &lt; n; j++)
        for (int i = 0; i &lt; n / 2; ++i)
          swap(mat[i][j], mat[n - i - 1][j]);
      return mat;
    };
    for (int i = 0; i &lt; 4; ++i)
      if (rot(mat) == target) return true;    
    return false;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1886-determine-whether-matrix-can-be-obtained-by-rotation/">花花酱 LeetCode 1886. Determine Whether Matrix Can Be Obtained By Rotation</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-1886-determine-whether-matrix-can-be-obtained-by-rotation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Jan 2021 21:10:47 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7990</guid>

					<description><![CDATA[<p>You are given a binary matrix&#160;matrix&#160;of size&#160;m x n, and you are allowed to rearrange the&#160;columns&#160;of the&#160;matrix&#160;in any order. Return&#160;the area of the largest submatrix&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/">花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</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 1727. Largest Submatrix With Rearrangements - 刷题找工作 EP380" width="500" height="281" src="https://www.youtube.com/embed/eX0lXwGu3OE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given a binary matrix&nbsp;<code>matrix</code>&nbsp;of size&nbsp;<code>m x n</code>, and you are allowed to rearrange the&nbsp;<strong>columns</strong>&nbsp;of the&nbsp;<code>matrix</code>&nbsp;in any order.</p>



<p>Return&nbsp;<em>the area of the largest submatrix within&nbsp;</em><code>matrix</code><em>&nbsp;where&nbsp;<strong>every</strong>&nbsp;element of the submatrix is&nbsp;</em><code>1</code><em>&nbsp;after reordering the columns optimally.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40536-pm.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[0,0,1],[1,1,1],[1,0,1]]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/12/29/screenshot-2020-12-30-at-40852-pm.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,0,1,0,1]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,1,0],[1,0,1]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[0,0],[0,0]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> As there are no 1s, no submatrix of 1s can be formed and the area is 0.</pre>



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



<ul><li><code>m == matrix.length</code></li><li><code>n == matrix[i].length</code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>matrix[i][j]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



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



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png" alt="" class="wp-image-7997" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-1-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/01/1727-ep380-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2.png" alt="" class="wp-image-7999" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/01/1727-ep380-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Preprocess each column, for col j, matrix[i][j] := length consecutive ones of col j.</p>



<pre class="wp-block-code;crayon:false"><code>&#091;0,0,1]    &#091;0,0,1]
&#091;1,1,1] =&gt; &#091;1,1,2]
&#091;1,0,1]    &#091;2,0,3]</code></pre>



<p>Then we enumerate ending row, for each ending row i, we sort row[i] in deceasing order</p>



<p>e.g. i = 2</p>



<pre class="wp-block-code;crayon:false"><code>&#091;0,0,1]                  &#091;-,-,-]
&#091;1,1,2] sort by row 2 =&gt; &#091;-,-,-]
&#091;2,0,3]                  &#091;3,2,0]</code></pre>



<p>row[2][1] = 3, means there is a 3&#215;1 all ones sub matrix, area = 3<br>row[2][2] = 2, means there is a 2&#215;2 all ones sub matrix, area = 4.</p>



<p>Time complexity: O(m*n*log(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:
  int largestSubmatrix(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    for (int j = 0; j &lt; n; ++j)
      for (int i = 1; i &lt; m; ++i)      
        if (matrix[i][j]) matrix[i][j] += matrix[i - 1][j];          
    
    int ans = 0;
    for (int i = 0; i &lt; m; ++i) {
      sort(rbegin(matrix[i]), rend(matrix[i]));
      for (int j = 0; j &lt; n; ++j)
        ans = max(ans, (j + 1) * matrix[i][j]);        
    }
    return ans;    
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1727-largest-submatrix-with-rearrangements/">花花酱 LeetCode 1727. Largest Submatrix With Rearrangements</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-1727-largest-submatrix-with-rearrangements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1672. Richest Customer Wealth</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Nov 2020 09:47:42 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7733</guid>

					<description><![CDATA[<p>You are given an&#160;m x n&#160;integer grid&#160;accounts&#160;where&#160;accounts[i][j]&#160;is the amount of money the&#160;i​​​​​​​​​​​th​​​​&#160;customer has in the&#160;j​​​​​​​​​​​th​​​​ bank. Return&#160;the&#160;wealth&#160;that the richest customer has. A customer&#8217;s&#160;wealth&#160;is the amount&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/">花花酱 LeetCode 1672. Richest Customer Wealth</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;<code>m x n</code>&nbsp;integer grid&nbsp;<code>accounts</code>&nbsp;where&nbsp;<code>accounts[i][j]</code>&nbsp;is the amount of money the&nbsp;<code>i​​​​​<sup>​​​​​​th</sup>​​​​</code>&nbsp;customer has in the&nbsp;<code>j​​​​​<sup>​​​​​​th</sup></code>​​​​ bank. Return<em>&nbsp;the&nbsp;<strong>wealth</strong>&nbsp;that the richest customer has.</em></p>



<p>A customer&#8217;s&nbsp;<strong>wealth</strong>&nbsp;is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum&nbsp;<strong>wealth</strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> accounts = [[1,2,3],[3,2,1]]
<strong>Output:</strong> 6
<strong>Explanation</strong><strong>:</strong>
<code>1st customer has wealth = 1 + 2 + 3 = 6
</code><code>2nd customer has wealth = 3 + 2 + 1 = 6
</code>Both customers are considered the richest with a wealth of 6 each, so return 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> accounts = [[1,5],[7,3],[3,5]]
<strong>Output:</strong> 10
<strong>Explanation</strong>: 
1st customer has wealth = 6
2nd customer has wealth = 10 
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.</pre>



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



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



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



<ul><li><code>m ==&nbsp;accounts.length</code></li><li><code>n ==&nbsp;accounts[i].length</code></li><li><code>1 &lt;= m, n &lt;= 50</code></li><li><code>1 &lt;= accounts[i][j] &lt;= 100</code></li></ul>



<h2><strong>Solution: Sum each row up</strong></h2>



<p>Time complexity: O(mn)<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:
  int maximumWealth(vector&lt;vector&lt;int&gt;&gt;&amp; accounts) {
    int ans = 0;
    for (const vector&lt;int&gt;&amp; row : accounts)
      ans = max(ans, accumulate(begin(row), end(row), 0));
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def maximumWealth(self, accounts: List[List[int]]) -&gt; int:
    return max(sum(account) for account in accounts)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/">花花酱 LeetCode 1672. Richest Customer Wealth</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-1672-richest-customer-wealth/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1632. Rank Transform of a Matrix</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1632-rank-transform-of-a-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1632-rank-transform-of-a-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 29 Oct 2020 03:38:19 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[cc]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7570</guid>

					<description><![CDATA[<p>Given an&#160;m x n&#160;matrix, return&#160;a new matrix&#160;answer&#160;where&#160;answer[row][col]&#160;is the&#160;rank&#160;of&#160;matrix[row][col]. The&#160;rank&#160;is an&#160;integer&#160;that represents how large an element is compared to other elements. It is calculated using the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1632-rank-transform-of-a-matrix/">花花酱 LeetCode 1632. Rank Transform of a Matrix</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 an&nbsp;<code>m x n</code>&nbsp;<code>matrix</code>, return&nbsp;<em>a new matrix&nbsp;</em><code>answer</code><em>&nbsp;where&nbsp;</em><code>answer[row][col]</code><em>&nbsp;is the&nbsp;</em><em><strong>rank</strong>&nbsp;of&nbsp;</em><code>matrix[row][col]</code>.</p>



<p>The&nbsp;<strong>rank</strong>&nbsp;is an&nbsp;<strong>integer</strong>&nbsp;that represents how large an element is compared to other elements. It is calculated using the following rules:</p>



<ul><li>The rank is an integer starting from&nbsp;<code>1</code>.</li><li>If two elements&nbsp;<code>p</code>&nbsp;and&nbsp;<code>q</code>&nbsp;are in the&nbsp;<strong>same row or column</strong>, then:<ul><li>If&nbsp;<code>p &lt; q</code>&nbsp;then&nbsp;<code>rank(p) &lt; rank(q)</code></li><li>If&nbsp;<code>p == q</code>&nbsp;then&nbsp;<code>rank(p) == rank(q)</code></li><li>If&nbsp;<code>p &gt; q</code>&nbsp;then&nbsp;<code>rank(p) &gt; rank(q)</code></li></ul></li><li>The&nbsp;<strong>rank</strong>&nbsp;should be as&nbsp;<strong>small</strong>&nbsp;as possible.</li></ul>



<p>It is guaranteed that&nbsp;<code>answer</code>&nbsp;is unique under the given rules.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/10/18/rank1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[1,2],[3,4]]
<strong>Output:</strong> [[1,2],[2,3]]
<strong>Explanation:</strong>
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] &gt; matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] &gt; matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] &gt; matrix[0][1], matrix[1][1] &gt; matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/10/18/rank2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[7,7],[7,7]]
<strong>Output:</strong> [[1,1],[1,1]]
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/10/18/rank3.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
<strong>Output:</strong> [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/10/18/rank4.jpg" alt=""/></figure>



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



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



<ul><li><code>m == matrix.length</code></li><li><code>n == matrix[i].length</code></li><li><code>1 &lt;= m, n &lt;= 500</code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= matrix[row][col] &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Union Find</strong></h2>



<p>Group cells by their values, process groups (cells that have the same value) in ascending order (smaller number has smaller rank).</p>



<p>For cells that are in the same row and same cols union them using union find, they should have the same rank which equals to max(max_rank_x[cols], max_rank_y[rows]) + 1.</p>



<p>Time complexity: O(m*n*(m+n))<br>Space complexity: O(m*n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class DSU {
public:
  DSU(int n): p_(n, -1) {}
  int find(int x) {
    return p_[x] == -1 ? x : p_[x] = find(p_[x]);
  }  
  void merge(int x, int y) {
    x = find(x), y = find(y);
    if (x != y) p_[x] = y;    
  }
private:
  vector&lt;int&gt; p_;
};

class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; matrixRankTransform(vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
    const int m = matrix.size();
    const int n = matrix[0].size();
    vector&lt;vector&lt;int&gt;&gt; ans(m, vector&lt;int&gt;(n));
    map&lt;int, vector&lt;pair&lt;int, int&gt;&gt;&gt; mp; // val -&gt; {positions}
    for (int y = 0; y &lt; m; ++y)
      for (int x = 0; x &lt; n; ++x)
        mp[matrix[y][x]].emplace_back(x, y);
    vector&lt;int&gt; rx(n), ry(m);
    for (const auto&amp; [val, ps]: mp) {
      DSU dsu(n + m);
      vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; cc(n + m); // val -&gt; {positions}
      for (const auto&amp; [x, y]: ps)
        dsu.merge(x, y + n);
      for (const auto&amp; [x, y]: ps)        
        cc[dsu.find(x)].emplace_back(x, y);      
      for (const auto&amp; ps: cc) {
        int rank = 1;
        for (const auto&amp; [x, y]: ps)
          rank = max(rank, max(rx[x], ry[y]) + 1);
        for (const auto&amp; [x, y]: ps)
          rx[x] = ry[y] = ans[y][x] = rank;   
      }      
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1632-rank-transform-of-a-matrix/">花花酱 LeetCode 1632. Rank Transform of a Matrix</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-1632-rank-transform-of-a-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1605. Find Valid Matrix Given Row and Column Sums</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1605-find-valid-matrix-given-row-and-column-sums/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1605-find-valid-matrix-given-row-and-column-sums/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 03 Oct 2020 23:14:45 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7445</guid>

					<description><![CDATA[<p>You are given two arrays&#160;rowSum&#160;and&#160;colSum&#160;of non-negative integers where&#160;rowSum[i]&#160;is the sum of the elements in the&#160;ith&#160;row and&#160;colSum[j]&#160;is the sum of the elements of the&#160;jth&#160;column of a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1605-find-valid-matrix-given-row-and-column-sums/">花花酱 LeetCode 1605. Find Valid Matrix Given Row and Column Sums</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 two arrays&nbsp;<code>rowSum</code>&nbsp;and&nbsp;<code>colSum</code>&nbsp;of non-negative integers where&nbsp;<code>rowSum[i]</code>&nbsp;is the sum of the elements in the&nbsp;<code>i<sup>th</sup></code>&nbsp;row and&nbsp;<code>colSum[j]</code>&nbsp;is the sum of the elements of the&nbsp;<code>j<sup>th</sup></code>&nbsp;column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.</p>



<p>Find any matrix of&nbsp;<strong>non-negative</strong>&nbsp;integers of size&nbsp;<code>rowSum.length x colSum.length</code>&nbsp;that satisfies the&nbsp;<code>rowSum</code>&nbsp;and&nbsp;<code>colSum</code>&nbsp;requirements.</p>



<p>Return&nbsp;<em>a 2D array representing&nbsp;<strong>any</strong>&nbsp;matrix that fulfills the requirements</em>. It&#8217;s guaranteed that&nbsp;<strong>at least one&nbsp;</strong>matrix that fulfills the requirements exists.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rowSum = [3,8], colSum = [4,7]
<strong>Output:</strong> [[3,0],
         [1,7]]
<strong>Explanation:</strong>
0th row: 3 + 0 = 0 == rowSum[0]
1st row: 1 + 7 = 8 == rowSum[1]
0th column: 3 + 1 = 4 == colSum[0]
1st column: 0 + 7 = 7 == colSum[1]
The row and column sums match, and all matrix elements are non-negative.
Another possible matrix is: [[1,2],
                             [3,5]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rowSum = [5,7,10], colSum = [8,6,8]
<strong>Output:</strong> [[0,5,0],
         [6,1,0],
         [2,0,8]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rowSum = [14,9], colSum = [6,9,8]
<strong>Output:</strong> [[0,9,5],
         [6,0,3]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rowSum = [1,0], colSum = [1]
<strong>Output:</strong> [[1],
         [0]]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> rowSum = [0], colSum = [0]
<strong>Output:</strong> [[0]]
</pre>



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



<ul><li><code>1 &lt;= rowSum.length, colSum.length &lt;= 500</code></li><li><code>0 &lt;= rowSum[i], colSum[i] &lt;= 10<sup>8</sup></code></li><li><code>sum(rows) == sum(columns)</code></li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Let a = min(row[i], col[j]), m[i][j] = a, row[i] -= a, col[j] -=a</p>



<p>Time complexity: O(m*n)<br>Space complexity: O(m*n)</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; restoreMatrix(vector&lt;int&gt;&amp; rowSum, vector&lt;int&gt;&amp; colSum) {
    const int m = rowSum.size();
    const int n = colSum.size();
    vector&lt;vector&lt;int&gt;&gt; ans(m, vector&lt;int&gt;(n));
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        ans[i][j] = min(rowSum[i], colSum[j]);
        rowSum[i] -= ans[i][j];
        colSum[j] -= ans[i][j];
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1605-find-valid-matrix-given-row-and-column-sums/">花花酱 LeetCode 1605. Find Valid Matrix Given Row and Column Sums</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/greedy/leetcode-1605-find-valid-matrix-given-row-and-column-sums/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1594. Maximum Non Negative Product in a Matrix</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1594-maximum-non-negative-product-in-a-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1594-maximum-non-negative-product-in-a-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Sep 2020 07:39:43 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7405</guid>

					<description><![CDATA[<p>You are given a&#160;rows x cols&#160;matrix&#160;grid.&#160;Initially, you&#160;are located at the top-left&#160;corner&#160;(0, 0),&#160;and in each step, you can only&#160;move right&#160;or&#160;down&#160;in the matrix. Among all possible paths&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1594-maximum-non-negative-product-in-a-matrix/">花花酱 LeetCode 1594. Maximum Non Negative Product in a Matrix</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 a&nbsp;<code>rows x cols</code>&nbsp;matrix&nbsp;<code>grid</code>.&nbsp;Initially, you&nbsp;are located at the top-left&nbsp;corner&nbsp;<code>(0, 0)</code>,&nbsp;and in each step, you can only&nbsp;<strong>move right&nbsp;or&nbsp;down</strong>&nbsp;in the matrix.</p>



<p>Among all possible paths starting from the top-left corner&nbsp;<code>(0, 0)</code>&nbsp;and ending in the bottom-right corner&nbsp;<code>(rows - 1, cols - 1)</code>, find the path with the&nbsp;<strong>maximum non-negative product</strong>. The product of a path is the product of all integers in the grid cells visited along the path.</p>



<p>Return the&nbsp;<em>maximum non-negative product&nbsp;<strong>modulo</strong>&nbsp;</em><code>10<sup>9</sup>&nbsp;+ 7</code>.&nbsp;<em>If the maximum product is&nbsp;<strong>negative</strong>&nbsp;return&nbsp;</em><code>-1</code>.</p>



<p><strong>Notice that the modulo is performed after getting the maximum product.</strong></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[-1,-2,-3],
&nbsp;              [-2,-3,-3],
&nbsp;              [-3,-3,-2]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> It's not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[<strong>1</strong>,-2,1],
&nbsp;              [<strong>1</strong>,<strong>-2</strong>,1],
&nbsp;              [3,<strong>-4</strong>,<strong>1</strong>]]
<strong>Output:</strong> 8
<strong>Explanation:</strong> Maximum non-negative product is in bold (1 * 1 * -2 * -4 * 1 = 8).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[<strong>1</strong>, 3],
&nbsp;              [<strong>0</strong>,<strong>-4</strong>]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Maximum non-negative product is in bold (1 * 0 * -4 = 0).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[ <strong>1</strong>, 4,4,0],
&nbsp;              [<strong>-2</strong>, 0,0,1],
&nbsp;              [ <strong>1</strong>,<strong>-1</strong>,<strong>1</strong>,<strong>1</strong>]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Maximum non-negative product is in bold (1 * -2 * 1 * -1 * 1 * 1 = 2).
</pre>



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



<ul><li><code>1 &lt;= rows, cols &lt;= 15</code></li><li><code>-4 &lt;= grid[i][j] &lt;= 4</code></li></ul>



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



<p>Use two dp arrays,</p>



<p>dp_max[i][j] := max product of matrix[0~i][0~j]<br>dp_min[i][j] := min product of matrix[0~i][0~j]</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxProductPath(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    constexpr int kMod = 1e9 + 7;
    const int m = grid.size();
    const int n = grid[0].size();
    vector&lt;vector&lt;long&gt;&gt; dp_max(m, vector&lt;long&gt;(n));
    vector&lt;vector&lt;long&gt;&gt; dp_min(m, vector&lt;long&gt;(n));
    dp_max[0][0] = dp_min[0][0] = grid[0][0];
    for (int i = 1; i &lt; m; ++i)
      dp_max[i][0] = dp_min[i][0] = dp_min[i - 1][0] * grid[i][0];
    for (int j = 1; j &lt; n; ++j)
      dp_max[0][j] = dp_min[0][j] = dp_min[0][j - 1] * grid[0][j];
    for (int i = 1; i &lt; m; ++i)
      for (int j = 1; j &lt; n; ++j) {        
        if (grid[i][j] &gt;= 0) {
          dp_max[i][j] = max(dp_max[i - 1][j], dp_max[i][j - 1]) * grid[i][j];
          dp_min[i][j] = min(dp_min[i - 1][j], dp_min[i][j - 1]) * grid[i][j];
        } else {
          dp_max[i][j] = min(dp_min[i - 1][j], dp_min[i][j - 1]) * grid[i][j];
          dp_min[i][j] = max(dp_max[i - 1][j], dp_max[i][j - 1]) * grid[i][j];
        }
      }
    return dp_max[m - 1][n - 1] &gt;= 0 ? dp_max[m - 1][n - 1] % kMod : -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1594-maximum-non-negative-product-in-a-matrix/">花花酱 LeetCode 1594. Maximum Non Negative Product in a Matrix</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-1594-maximum-non-negative-product-in-a-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1582. Special Positions in a Binary Matrix</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1582-special-positions-in-a-binary-matrix/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1582-special-positions-in-a-binary-matrix/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Sep 2020 05:22:59 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[pre compute]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7360</guid>

					<description><![CDATA[<p>Given a&#160;rows x cols&#160;matrix&#160;mat,&#160;where&#160;mat[i][j]&#160;is either&#160;0&#160;or&#160;1,&#160;return&#160;the number of special positions in&#160;mat. A position&#160;(i,j)&#160;is called&#160;special&#160;if&#160;mat[i][j] == 1&#160;and all other elements in row&#160;i&#160;and column&#160;j&#160;are&#160;0&#160;(rows and columns are&#160;0-indexed). Example&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1582-special-positions-in-a-binary-matrix/">花花酱 LeetCode 1582. Special Positions in a Binary Matrix</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&nbsp;<code>rows x cols</code>&nbsp;matrix&nbsp;<code>mat</code>,&nbsp;where&nbsp;<code>mat[i][j]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>,&nbsp;return&nbsp;<em>the number of special positions in&nbsp;<code>mat</code>.</em></p>



<p>A position&nbsp;<code>(i,j)</code>&nbsp;is called&nbsp;<strong>special</strong>&nbsp;if&nbsp;<code>mat[i][j] == 1</code>&nbsp;and all other elements in row&nbsp;<code>i</code>&nbsp;and column&nbsp;<code>j</code>&nbsp;are&nbsp;<code>0</code>&nbsp;(rows and columns are&nbsp;<strong>0-indexed</strong>).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,0,0],
&nbsp;             [0,0,<strong>1</strong>],
&nbsp;             [1,0,0]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> (1,2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[<strong>1</strong>,0,0],
&nbsp;             [0,<strong>1</strong>,0],
&nbsp;             [0,0,<strong>1</strong>]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> (0,0), (1,1) and (2,2) are special positions. 
</pre>



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



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



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



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



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



<ul><li><code>rows == mat.length</code></li><li><code>cols == mat[i].length</code></li><li><code>1 &lt;= rows, cols &lt;= 100</code></li><li><code>mat[i][j]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Sum for each row and column</strong></h2>



<p>Brute force:<br>Time complexity: O(R*C*(R+C))<br>Space complexity: O(1)</p>



<p>We can pre-compute the sums for each row and each column, ans = sum(mat[r][c] == 1 and rsum[r] == 1 and csum[c] == 1)</p>



<p>Time complexity: O(R*C)<br>Space complexity: O(R+C)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int numSpecial(vector&lt;vector&lt;int&gt;&gt;&amp; mat) {
    const int rows = mat.size();
    const int cols = mat[0].size();
    vector&lt;int&gt; rs(rows);
    vector&lt;int&gt; cs(cols);
    for (int r = 0; r &lt; rows; ++r)
      for (int c = 0; c &lt; cols; ++c) {
        rs[r] += mat[r][c];
        cs[c] += mat[r][c];
      }
    int ans = 0;
    for (int r = 0; r &lt; rows; ++r)
      for (int c = 0; c &lt; cols; ++c)
        ans += mat[r][c] &amp;&amp; rs[r] == 1 &amp;&amp; cs[c] == 1;      
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1582-special-positions-in-a-binary-matrix/">花花酱 LeetCode 1582. Special Positions in a Binary Matrix</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-1582-special-positions-in-a-binary-matrix/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
