Maximal Square || LeetCode

dp.

#define MAX 1000
int rowLeft[MAX][MAX];
int colUp[MAX][MAX];
int dp[MAX][MAX];
void calRow(char **matrix,int matrixRowSize,int matrixColSize){
    int i,j;
    for(i=0;i<matrixRowSize;++i){
        for(j=0;j<matrixColSize;++j)
        {
            if(matrix[i][j]=='1')
            {
                if(j==0)rowLeft[i][j]=1;
                else rowLeft[i][j]=rowLeft[i][j-1]+1;
            }
            else rowLeft[i][j]=0;
        }
    }
}
void calCol(char **matrix,int matrixRowSize,int matrixColSize){
    int i,j;
    for(i=0;i<matrixRowSize;++i)
    {
        for(j=0;j<matrixColSize;++j)
        {
            if(matrix[i][j]=='1'){
                if(i==0)colUp[i][j]=1;
                else colUp[i][j]=colUp[i-1][j]+1;
            }
            else colUp[i][j]=0;
        }
    }
}
int min(int a,int b,int c){
    int t;
    t=(a<b?a:b);
    t=(t<c?t:c);
    return t;
}
int maximalSquare(char** matrix, int matrixRowSize, int matrixColSize) {
    int i,j,maxSquare=0;
    calRow(matrix,matrixRowSize,matrixColSize);
    calCol(matrix,matrixRowSize,matrixColSize);
    for(i=0;i<matrixRowSize;++i)
    {   for(j=0;j<matrixColSize;++j)
        {
            if(i==0||j==0)
                dp[i][j]=(matrix[i][j]=='1'?1:0);
            else dp[i][j]=min(dp[i-1][j-1]+1,rowLeft[i][j],colUp[i][j]);
            maxSquare=(maxSquare>dp[i][j]?maxSquare:dp[i][j]);
        }
    }
    return maxSquare*maxSquare;
}

  

我这个空间复杂度有点高

posted on 2015-06-05 21:45  coderlt  阅读(354)  评论(1编辑  收藏  举报

导航