221. Maximal Square

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.

求一个矩阵中的最大的一个正方形,这个正方形中只包含'1'。

看到这道题就想到了之前做过的Maximal Rectange,这两道题是很相似的,因为正方形式长方形的一种特例,我们只需要按照Maximal Rectange的做法去计算,等计算长方形面积时,只需要找到这个长方形中能放下的最大正方形的面积就行了。

利用一个数组将矩阵转换为多个柱形图,计算柱形图中能放下的最大正方形面积。

#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <stack>
using namespace std;
int maximalSquarehelper(vector<int>& dp,int d)
{
	int max = 0;
	stack<int> stk;
	dp.push_back(0);
	for (int i = 0; i < dp.size(); i++)
	{
		if (stk.empty() || dp[i] >= dp[stk.top()])stk.push(i);
		else
		{
			int peek = stk.top();
			stk.pop();
			int temp = stk.empty() ? (dp[peek] < i ? dp[peek] * dp[peek] : i * i) : (dp[peek] < (i - 1 - stk.top()) ? dp[peek] * dp[peek] : (i - 1 - stk.top()) * (i - 1 - stk.top()));
			max = max > temp ? max : temp;
			i--;
		}
	}
	dp.pop_back();
	return max;
}
int maximalSquare(vector<vector<char>>& matrix)
{
	int rows = matrix.size();
	if (rows == 0)return 0;
	int cols = matrix[0].size();
	if (cols == 0)return 0;
	vector<int> dp(cols, 0);
	int max = 0;
	for (int i = 0; i < rows; i++)
	{
		for (int j = 0; j < cols; j++)
		{
			if (matrix[i][j] == '0')dp[j] = 0;
			else dp[j]++;
		}
		int temp = maximalSquarehelper(dp, i);
		max = max > temp ? max : temp;
	}
	return max;
}
int main()
{
	vector<vector<char>> matrix{
	{'1','0','1','0','0','1','1','1','0'},
	{'1','1','1','0','0','0','0','0','1'},
	{'0','0','1','1','0','0','0','1','1'},
	{'0','1','1','0','0','1','0','0','1'},
	{'1','1','0','1','1','0','0','1','0'},
	{'0','1','1','1','1','1','1','0','1'},
	{'1','0','1','1','1','0','0','1','0'},
	{'1','1','1','0','1','0','0','0','1'},
	{'0','1','1','1','1','0','0','1','0'},
	{'1','0','0','1','1','1','0','0','0'} };
	cout << maximalSquare(matrix) << endl;
	system("pause");
	return 0;
}
上诉代码的运行结果为4。最好情况下的时间复杂度为O(MNN)(此时dp数组中的元素都是递增的),M,N分别是矩阵的行数和列数,
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页