221. Maximal Square
Medium

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0 Output: 4
 
 

To appy DP, we define the state as the maximal size (square = size * size) of the square that can be formed till point (i, j), denoted as dp[i][j].

For the topmost row (i = 0) and the leftmost column (j = 0), we have dp[i][j] = matrix[i][j] - '0', meaning that it can at most form a square of size 1 when the matrix has a '1'in that cell.

When i > 0 and j > 0, if matrix[i][j] = '0', then dp[i][j] = 0 since no square will be able to contain the '0' at that cell. If matrix[i][j] = '1', we will have dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1, which means that the square will be limited by its left, upper and upper-left neighbors.

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) {
return ;
}
int m = matrix.size(), n = matrix[].size(), sz = ;
vector<vector<int>> dp(m, vector<int>(n, ));
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (!i || !j || matrix[i][j] == '') {
dp[i][j] = matrix[i][j] - '';
} else {
dp[i][j] = min(dp[i - ][j - ], min(dp[i - ][j], dp[i][j - ])) + ;
}
sz = max(dp[i][j], sz);
}
}
return sz * sz;
}
};

In the above code, it uses O(mn) space. Actually each time when we update dp[i][j], we only need dp[i-1][j-1]dp[i-1][j] (the previous row) and dp[i][j-1] (the current row). So we may just keep two rows.

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) {
return ;
}
int m = matrix.size(), n = matrix[].size(), sz = ;
vector<int> pre(n, ), cur(n, );
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
if (!i || !j || matrix[i][j] == '') {
cur[j] = matrix[i][j] - '';
} else {
cur[j] = min(pre[j - ], min(pre[j], cur[j - ])) + ;
}
sz = max(cur[j], sz);
}
fill(pre.begin(), pre.end(), );
swap(pre, cur);
}
return sz * sz;
}
};

Furthermore, we may only use just one vector (thanks to @stellari for sharing the idea).

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if (matrix.empty()) {
return ;
}
int m = matrix.size(), n = matrix[].size(), sz = , pre;
vector<int> cur(n, );
for (int i = ; i < m; i++) {
for (int j = ; j < n; j++) {
int temp = cur[j];
if (!i || !j || matrix[i][j] == '') {
cur[j] = matrix[i][j] - '';
} else {
cur[j] = min(pre, min(cur[j], cur[j - ])) + ;
}
sz = max(cur[j], sz);
pre = temp;
}
}
return sz * sz;
}
};

LeetCode | DP专题详解的更多相关文章

  1. 状压DP入门详解+题目推荐

    在动态规划的题型中,一般叫什么DP就是怎么DP,状压DP也不例外 所谓状态压缩,一般是通过用01串表示状态,充分利用二进制数的特性,简化计算难度.举个例子,在棋盘上摆放棋子的题目中,我们可以用1表示当 ...

  2. Leetcode之动态规划(DP)专题-详解983. 最低票价(Minimum Cost For Tickets)

    Leetcode之动态规划(DP)专题-983. 最低票价(Minimum Cost For Tickets) 在一个火车旅行很受欢迎的国度,你提前一年计划了一些火车旅行.在接下来的一年里,你要旅行的 ...

  3. LeetCode专题——详解搜索算法中的搜索策略和剪枝

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题第20篇文章,今天讨论的是数字组合问题. 描述 给定一个int类型的候选集,和一个int类型的target,要求返 ...

  4. Leetcode之广度优先搜索(BFS)专题-详解429. N叉树的层序遍历(N-ary Tree Level Order Traversal)

    Leetcode之广度优先搜索(BFS)专题-429. N叉树的层序遍历(N-ary Tree Level Order Traversal) 给定一个 N 叉树,返回其节点值的层序遍历. (即从左到右 ...

  5. LeetCode dp专题

    1. 动态规划的适用场景 动态规划常常适用于有重叠子问题和最优子结构性质的问题,动态规划方法所耗时间往往远少于朴素解法. 2. 动态规划的基本思想 动态规划背后的基本思想非常简单.大致上,若要解一个给 ...

  6. 分布式专题——详解Google levelDB底层原理

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是分布式专题的第10篇文章,我们继续来聊聊LSMT这个数据结构. LSMT是一个在分布式系统当中应用非常广泛,并且原理直观简单的数据结构 ...

  7. 【动态规划】树形DP完全详解!

    蒟蒻大佬时隔三个月更新了!!拍手拍手 而且是更新了几篇关于DP的文章(RioTian狂喜) 现在赶紧学习和复习一下树形DP.... 树形DP基础:Here,CF上部分树形DP练习题:Here \[QA ...

  8. poj1417 true liars(并查集 + DP)详解

    这个题做了两天了.首先用并查集分类是明白的, 不过判断是否情况唯一刚开始用的是搜索.总是超时. 后来看别人的结题报告, 才恍然大悟判断唯一得用DP. 题目大意: 一共有p1+p2个人,分成两组,一组p ...

  9. LeetCode Permutations问题详解

    题目一 permutations 题目描述 Given a collection of numbers, return all possible permutations. For example,[ ...

随机推荐

  1. springboot与springcloud版本不对应导致报错java.lang.NoSuchMethodError: org.springframework.boot.builder.SpringApplicationBuilder.<init>([Ljava/lang/Object;)V

    springboot启动报错: 10:31:50.221 [main] ERROR org.springframework.boot.SpringApplication - Application r ...

  2. pytorch 图片处理.md

    本篇所有代码位置链接

  3. SQL Server代码的一种学习方法

    使用SQL Server Management Studio的操作过程中,界面上方都可以生成sql脚本代码. 如新建数据库时: CREATE DATABASE [db_New] ON PRIMARY ...

  4. Golang ioutil.ReadDir 读取目录下的内容并排序

    之前写的https://www.cnblogs.com/pu369/p/10620731.html一文中,也有对slice的排序,但代码乱的自己也看不下去了. 参考https://blog.csdn. ...

  5. psd缩略图上传组件

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  6. vue大文件上传断点续传解决方案

    之前仿造uploadify写了一个HTML5版的文件上传插件,没看过的朋友可以点此先看一下~得到了不少朋友的好评,我自己也用在了项目中,不论是用户头像上传,还是各种媒体文件的上传,以及各种个性的业务需 ...

  7. audio 预加载

    http://www.w3school.com.cn/tags/av_event_loadeddata.asp var audio = document.createElement("aud ...

  8. epplus动态合并列数据

    private static void SetColMerge(DataTable tb, ExcelWorksheet worksheet, string dtColumnName) { KeyVa ...

  9. [集训队作业2018]蜀道难——TopTree+贪心+树链剖分+链分治+树形DP

    题目链接: [集训队作业2018]蜀道难 题目大意:给出一棵$n$个节点的树,要求给每个点赋一个$1\sim n$之内的权值使所有点的权值是$1\sim n$的一个排列,定义一条边的权值为两端点权值差 ...

  10. 3.开始使用Spring Cloud实战微服务

                     开始使用Spring Cloud实战微服务 3.1. Spring Cloud实战前提 3.1.1. 需要的技术储备 语言方面:可以使用Java.scala.Groo ...