LeetCode-Maximal Square-解题报告

来源:互联网 发布:telnet ip 端口 linux 编辑:程序博客网 时间:2024/06/05 18:42

原题链接https://leetcode.com/problems/maximal-square/


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

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4. 


以前刷acm题的时候也遇到过类似的题,使用动态规划就可以解决

ab

cd

转移方程:dp[a] = 1 + Min(dp[b], dp[c], dp[d]) 表示以a这个坐标为左上角的正方形的边长大小=b和c和d的最小值。每个不为0的正方形的边长为1.

因为我使用的是一维数组,所以需要将二维映射到一维。

为了方便编程,我将矩阵的长宽分别加1。


class Solution {public:    int maximalSquare(vector<vector<char> >& matrix) {        if (matrix.size() == 0)return 0;int l = matrix.size();int w = matrix[0].size();vector<int>dp((l + 1)*(w + 1), 0);int ans = 0;for (int i = l - 1; i >= 0; --i){for (int j = w - 1; j >= 0; --j){if (matrix[i][j] != '0'){int a = (w + 1)*i + j;int b = a + 1;int c = a + w + 1;int d = c + 1;dp[a] = 1 + Min(dp[b], dp[c], dp[d]);if (dp[a] > ans)ans = dp[a];}}}return ans*ans;}int Min(int& b, int& c, int d){int min = b;if (min > c)min = c;if (min > d)min = d;return min;}};


0 0
原创粉丝点击