您的位置:首页 > 其它

[leetcode] Maximal Square

2015-06-04 21:59 417 查看
From : 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.

public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0) {
return 0;
}
int max = 0, m = matrix.length, n = matrix[0].length;
for(int i=0; i<m && (m-i)*(m-i)>max; ++i) {
for(int j=0; j<n && (n-j)*(n-j)>max; j++) {
if(matrix[i][j] == '1') {
int a = area(matrix, i, j, m, n, max);
if(a > max) {
max = a;
}
}
}
}
return max;
}

private int area(char[][] mt, int sti, int stj, int m, int n, int max) {
int i=sti, a=0;
int l = n; // minimum length
while(i < m) {
// boundry
int k = i-sti+1;

int j = stj;
while(j<n && mt[i][j]!='0') {
++j;
}
if(j-stj < l) {
l = j-stj;
}

// area
int ta = l*l;
if(k < l) {
ta = k*k;
}
if(ta > a) {
a = ta;
}
// try stop
if(k >= l || l*l <= max) {
break;
}
++i;
}
return a;
}
}


class Solution {
public:
void checkSquare(vector<vector<char>>& matrix, int stRow, int stCol,int rows, int cols, int& max) {
int j, i=stRow, col = cols;
while(i < rows) {
j = stCol;
while(j<cols && matrix[i][j]!='0') j++;
if((j-stCol)*(j-stCol) <= max) return;
if(j-stCol < col) col = j-stCol;
if(++i-stRow>col) return;
if((i-stRow)*(i-stRow) > max) max = (i-stRow)*(i-stRow);
}
}

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