LeetCode-Maximal Square-解题报告

原题链接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 0
1 0 1 1 1
1 1 1 1 1
1 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;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值