您的位置:首页 > 其它

leetcode 221. Maximal Square

2017-11-10 10:10 155 查看
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.

vec[i][j] 代表以这个点为右下角的正方形的最大边长

class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix)
{
int height = matrix.size();
if (height == 0)
return 0;
int width = matrix[0].size();
vector<vector<int>> vec(height, vector<int> (width, 0));
int result = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (matrix[i][j] == '1')
{
vec[i][j] = 1;
if (i > 0 && j > 0)
vec[i][j] += min(min(vec[i-1][j], vec[i][j-1]), vec[i-1][j-1]);
}
result = max(result, vec[i][j]);
}
}
return result * result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: