leetcode 221: Maximal Square

Use DP, and dp[i][j] means at matrix[i][j] the maximal square's size. First, initialize the first row and column which is obvious. Then you need to find the minimum number among dp[i-1][j-1], dp[i-1][j] and dp[i][j-1]. This minimum number means the distance you can reach as a sqare along the diagonal direction. Then update dp[i][j].

For example,

1 1

1 1

dp[0][0]=1, dp[0][1]=1, dp[1][0]=1, minimum number is 1. So dp[1][1] can go 1 along the diagonal. So dp[1][1]+=num+sqrt(num)*2;

If the matrix is

1 0

1 1

Then the minimum number is 0. So dp[1][1]=1;

You can try some bigger matrix to understand this.

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(matrix.empty())
            return 0;
        int m=matrix.size();
        int n=matrix[0].size();
        vector<vector<int> > dp(m,vector<int>(n,1));
        int res=0;
        for(int i=0;i<m;i++)
        {
            dp[i][0]=matrix[i][0]=='1';
            if(dp[i][0])
                res=1;
        }
        for(int i=1;i<n;i++)
        {
            dp[0][i]=matrix[0][i]=='1';
            if(dp[0][i])
                res=1;
        }
        for(int i=1;i<m;i++)
            for(int j=1;j<n;j++)
            {
                if(matrix[i][j]=='0')
                {
                    dp[i][j]=0;
                    continue;
                }
                int num=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]));
                dp[i][j]+=num+sqrt(num)*2;
                if(dp[i][j]>res)
                    res=dp[i][j];
            }
        return res;
    }
};


發佈了186 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章