当前位置:网站首页>221. Largest square ● &1277. Square submatrix with statistics all 1 ● ●
221. Largest square ● &1277. Square submatrix with statistics all 1 ● ●
2022-07-23 21:01:00 【keep_ fan】
221. The largest square ●●
describe
In a ‘0’ and ‘1’ In the two-dimensional matrix , Found contains only ‘1’ The largest square of , And return its area .
Example
Input :matrix = [[“1”,“0”,“1”,“0”,“0”],[“1”,“0”,“1”,“1”,“1”],[“1”,“1”,“1”,“1”,“1”],[“1”,“0”,“0”,“1”,“0”]]
Output :4
Answer key
1. Violence solution ( Overtime )
To find the area of the largest square , First, you need to find the side length of the largest square , Then calculate the square of the maximum side length .
Violence is the simplest and most intuitive approach , The specific methods are as follows :
- Traverse every element in the matrix , Every encounter 1, Then take this element as a square top left corner ;
- After determining the upper left corner of the square , Calculate the side length of the largest possible square according to the row and column in the upper left corner ( The range of the square cannot exceed the number of rows and columns of the matrix ), Look for only 1 The largest square of ;
- Add a new row at the bottom and a new column at the right , Judge whether the newly added rows and columns satisfy that all elements are 1.
- Time complexity : O ( m n min ( m , n ) 2 ) O(mn \min(m,n)^2) O(mnmin(m,n)2), among m and n Is the number of rows and columns of the matrix .
– You need to traverse the entire matrix to find each 1, The time complexity of traversing the matrix is O(mn)O(mn).
– For every possible square , Its side length does not exceed m and n Minimum of , You need to traverse each element in the square to determine whether it only contains 1, The time complexity of traversing a square is O ( min ( m , n ) 2 ) O(\min(m,n)^2) O(min(m,n)2). - Spatial complexity : O ( 1 ) O(1) O(1). The additional space complexity used is constant .
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int maxArea = 0;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(matrix[i][j] == '1'){
// (i, j) Is the upper-left coordinate
int minLen = n+m; // Continuous on the column 1 The minimum length of
for(int k = j; k < n; ++k){
// Traverse each column
if(k - j + 1 > minLen) break; // The side length of the row where the current column is located is greater than the minimum length , Out of the loop
int len = 0; // Record the continuous 1 The number of
for(int l = i; l < m; ++l){
if(l-i+1 > minLen) break; // The current column side length is greater than the minimum length , Out of the loop
if(matrix[l][k] == '0') break;
++len;
}
maxArea = max(maxArea, min(len, k-j+1)*min(len, k-j+1)); // After traversing a column , Update the current maximum area , Side length is min( Column length , governor )
minLen = min(len, minLen); // Update minimum length
}
}
}
}
return maxArea;
}
};
2. Dynamic programming
dp[i][j]Express Withmatrix[i][j]by The lower right corner when , Contains only 1 The square of Maximum side length .- Initialize the first row and the first column ,‘1’ Is the side length setting 1, Otherwise 0;
matrix[i][j] == '0': dp[i][j] = 0;matrix[i][j] == '1':dp[i][j] = min(min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1]) + 1;- From left to right , Traverse from top to bottom .
- Time complexity : O ( m n ) O(mn) O(mn), among m and n Is the number of rows and columns of the matrix . You need to traverse each element in the original matrix to calculate dp Value .
- Spatial complexity : O ( m n ) O(mn) O(mn), among m and n Is the number of rows and columns of the matrix . Create a matrix with the same size as the original matrix dp.
Due to the dp(i,j) From above 、 Three adjacent positions on the left and upper left dp Values determine , Therefore, two one-dimensional arrays can be used for state transition , Space complexity is optimized to O(n).

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int m = matrix.size(), n = matrix[0].size(), maxLen = 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
// Boundary condition treatment
for(int i = 0; i < m; ++i) if(matrix[i][0] == '1'){
dp[i][0] = 1; maxLen = 1;}
for(int j = 0; j < n; ++j) if(matrix[0][j] == '1'){
dp[0][j] = 1; maxLen = 1;}
for(int i = 1; i < m; ++i){
for(int j = 1; j < n; ++j){
if(matrix[i][j] == '1'){
dp[i][j] = min(min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1]) + 1;
maxLen = max(maxLen, dp[i][j]);
}
}
}
return maxLen * maxLen;
}
};
1277. The statistics are all 1 Square submatrix of ●●
describe
To give you one m * n Matrix , The elements in the matrix are not 0 Namely 1, Please count and return all the data 1 Composed of Square Number of submatrixes .
Example
Input :matrix =
[
[0,1,1,1],
[1,1,1,1],
[0,1,1,1]
]
Output :15
explain :
Side length is 1 What's the square of 10 individual .
Side length is 2 What's the square of 4 individual .
Side length is 3 What's the square of 1 individual .
The total number of squares = 10 + 4 + 1 = 15.
Answer key
Dynamic programming
And 221. The largest square ●● similar , Add up the sum of squares for each calculation , With (i, j) It's in the lower right corner Number of squares Is the maximum side length dp[i][j], Pay attention to the treatment of boundary conditions ,(0,0) It can't be repeated .
class Solution {
public:
int countSquares(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size(), sum = 0;
vector<vector<int>> dp(m, vector<int>(n, 0));
for(int i = 0; i < m; ++i) if(matrix[i][0] == 1){
dp[i][0] = 1; ++sum;}
for(int j = 1; j < n; ++j) if(matrix[0][j] == 1){
dp[0][j] = 1; ++sum;}
for(int i = 1; i < m; ++i){
for(int j = 1; j < n; ++j){
if(matrix[i][j] == 1){
dp[i][j] = min(min(dp[i-1][j-1], dp[i-1][j]), dp[i][j-1]) + 1;
sum += dp[i][j];
}
}
}
return sum;
}
};
边栏推荐
- LU_ Asr01 voice module usage
- [Yunxiang book club No. 13] Chapter IV packaging format and coding format of audio files
- The best time to plant trees is now
- 2022.7.11 MySQL job
- [shader realizes roundwave circular ripple effect _shader effect Chapter 6]
- Cesium knockout怎么用?
- Vite3 learning records
- 高数下|三重积分的计算1|高数叔|手写笔记
- 视觉slam学习|基础篇01
- Stm32c8t6 driven lidar (I)
猜你喜欢
![[wechat applet] do you know about applet development?](/img/3d/da58255aeb6bf6bc5021d988906bcc.png)
[wechat applet] do you know about applet development?

【攻防世界WEB】难度四星12分进阶题:FlatScience

【创建 Birthday Card 应用】

TypeScript基础
![[kernel] platform bus model for driving development and learning](/img/69/f600e4e6173491955ab90e92577450.png)
[kernel] platform bus model for driving development and learning

Chapter 3 business function development (creating clues)

【持续更新】树莓派启动与故障系列集锦

221. 最大正方形 ●● & 1277. 统计全为 1 的正方形子矩阵 ●●

第十二天:续第十一天(BGP相关知识)

Connect with Hunan Ca and use U_ Key login
随机推荐
-2021最新对比学习(Contrastive Learning)相关必读论文整理分享
模块化开发
大三实习生,字节跳动面经分享,已拿Offer
221. 最大正方形 ●● & 1277. 统计全为 1 的正方形子矩阵 ●●
Microservice architecture vs single service architecture [what can Huawei cloud service do in the microservice mode]
做一个有职业操守的软件匠人
微服务架构 VS 单体服务架构【华为云服务在微服务模式里可以做什么】
【Scratch画图100例】图46-scratch绘制花朵 少儿编程 scratch编程画图案例教程 考级比赛画图集训案例
Cesium knockout怎么用?
Addon plugin 003 for CDR plugin development - awareness solution (SLN) and project (csproj) files
1063 Set Similarity
HDU - 2586 How far away ? (multiply LCA)
“脉”向未来!华为云MRS助力脉脉迁移平滑上云
高数下|二重积分的计算4|高数叔|手写笔记
Green-Tao 定理 (4): 能量增量方法
【云驻共创】天天写SQL,你遇到了哪些神奇的特性?
[Yunxiang book club No. 13] Chapter IV packaging format and coding format of audio files
最小生成树:Kruskal
如何在面试中介绍自己的项目经验
OpenLayers官方实例全集