您的位置:首页 > 其它

Maximal Square

2016-09-07 09:19 176 查看
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.

Example

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
.

Analyse: Let dp[i][j] represents the maximum side of a square whose right bottom element is matrix[i][j].

dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1

Runtime: 124ms

class Solution {
public:
/**
* @param matrix: a matrix of 0 and 1
* @return: an integer
*/
int maxSquare(vector<vector<int> > &matrix) {
// write your code here
if (matrix.empty() || matrix[0].empty()) return 0;

int m = matrix.size(), n = matrix[0].size();
vector<vector<int> > dp(m, vector<int>(n, 0));

int result = 0;
// initialize the first row
for (int i = 0; i < n; i++) {
if (matrix[0][i]) {
dp[0][i] = 1;
result = 1;
}
}

// initialize the first column
for (int i = 0; i < m; i++) {
if (matrix[i][0]) {
dp[i][0] = 1;
result = 1;
}
}

// calculate the remaining part
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j]) {
dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1;
result = max(result, dp[i][j]);
}
else dp[i][j] = 0;
}
}
return result * result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: