221. Maximal Square

来源:互联网 发布:安畅网络水军平台 编辑:程序博客网 时间:2024/04/30 15:52

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.

这道题和之前的85. Maximal Rectangle很像,只是一个求矩形,一个求正方形。
第一种方法:类似85题,只是细节有些修改
堆栈法

class Solution {public:    int maximalSquare(vector<vector<char> >& matrix)     {        if(matrix.size()==0 || matrix[0].size()==0)            return 0;        int m=matrix.size();        int n=matrix[0].size();        int i,j,area=0;        vector<int>heights(n,0);        for(i=0;i<m;i++)        {            for(j=0;j<n;j++)            {                if(matrix[i][j]=='1')                    heights[j]+=1;                else                    heights[j]=0;            }            area=area>largestSquareArea(heights)?area:largestSquareArea(heights);        }        return area;    }    int largestSquareArea(vector<int>& heights)     {        int area=0,i;        stack<int>temp;        for(i=0;i<heights.size();i++)        {            if(temp.empty())                temp.push(heights[i]);            else            {                if(heights[i]>=temp.top())                    temp.push(heights[i]);                else                {                    int count=1;                    while(!temp.empty()&&heights[i]<temp.top())                    {                        int length=temp.top()<count?temp.top():count;                        area=length*length>area?length*length:area;                        temp.pop();                        count++;                    }                    while(count)                    {                        temp.push(heights[i]);                        count--;                    }                }            }        }        int num=1;        while(!temp.empty())        {            int length=temp.top()<num?temp.top():num;            area=length*length>area?length*length:area;            num++;            temp.pop();        }        return area;    }};

暴力求解法

class Solution {public:    int  maximalSquare(vector<vector<char> >& matrix)     {        if(matrix.size()==0||matrix[0].size()==0)            return 0;        int m=matrix.size();        int n=matrix[0].size();        vector<vector<int> >dp(m,vector<int>(n,0));        int i,j,k;        for(i=0;i<m;i++)            dp[i][n-1]=matrix[i][n-1]-'0';        for(i=0;i<m;i++)            for(j=n-2;j>=0;j--)            {                if(matrix[i][j]=='0')                    dp[i][j]=0;                else                    dp[i][j]=1+dp[i][j+1];            }        int area=0;        for(i=0;i<m;i++)            for(j=0;j<n;j++)            {                if((m-i)*(n-j)<=area)                    break;                int width=dp[i][j];                for(k=i;k<m;k++)                {                    if(width<k-i+1)                            break;                    if(width*(m-i)<=area)                            break;                    width=dp[k][j]<width?dp[k][j]:width;                    if(width==k-i+1)                        area=(k-i+1)*width>area?(k-i+1)*width:area;                }            }        return area;    }};

Well, this problem desires for the use of dynamic programming. They key to any DP problem is to come up with the state equation. In this problem, we define the state to be the maximal size of the square that can be achieved at point (i, j), denoted as P[i][j]. Remember that we use size instead of square as the state (square = size^2).

Now let’s try to come up with the formula for P[i][j].

First, it is obvious that for the topmost row (i = 0) and the leftmost column (j = 0), P[i][j] = matrix[i][j]. This is easily understood. Let’s suppose that the topmost row of matrix is like [1, 0, 0, 1]. Then we can immediately know that the first and last point can be a square of size 1 while the two middle points cannot make any square, giving a size of 0. Thus, P = [1, 0, 0, 1], which is the same as matrix. The case is similar for the leftmost column. Till now, the boundary conditions of this DP problem are solved.

Let’s move to the more general case for P[i][j] in which i > 0 and j > 0. First of all, let’s see another simple case in which matrix[i][j] = 0. It is obvious that P[i][j] = 0 too. Why? Well, since matrix[i][j] = 0, no square will contain matrix[i][j]. According to our definition of P[i][j], P[i][j] is also 0.

Now we are almost done. The only unsolved case is matrix[i][j] = 1. Let’s see an example.

Suppose matrix = [[0, 1], [1, 1]], it is obvious that P[0][0] = 0, P[0][1] = P[1][0] = 1, what about P[1][1]? Well, to give a square of size larger than 1 in P[1][1], all of its three neighbors (left, up, left-up) should be non-zero, right? In this case, the left-up neighbor P[0][0] = 0, so P[1][1] can only be 1, which means that it contains the square of itself.

Now you are near the solution. In fact, P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1 in this case.

Taking all these together, we have the following state equations.

P[0][j] = matrix[0][j] (topmost row);
P[i][0] = matrix[i][0] (leftmost column);
For i > 0 and j > 0: if matrix[i][j] = 0, P[i][j] = 0; if matrix[i][j] = 1, P[i][j] = min(P[i - 1][j], P[i][j - 1], P[i - 1][j - 1]) + 1.
第三种方法:动态规划

class Solution {public:    int maximalSquare(vector<vector<char> >& matrix)     {        if(matrix.size()==0 || matrix[0].size()==0)            return 0;        int m=matrix.size();        int n=matrix[0].size();        int maxside=0;        vector<vector<int> >dp(m,vector<int>(n,0));        int i,j;        for(i=0;i<m;i++)        {            dp[i][0]=matrix[i][0]-'0';            maxside=max(maxside,dp[i][0]);        }        for(j=1;j<n;j++)        {            dp[0][j]=matrix[0][j]-'0';            maxside=max(maxside,dp[0][j]);        }        for(i=1;i<m;i++)            for(j=1;j<n;j++)            {                if(matrix[i][j]=='1')                {                    dp[i][j]=min(dp[i-1][j],min(dp[i-1][j-1],dp[i][j-1]))+1;                    maxside=max(maxside,dp[i][j]);                }            }        return maxside*maxside;    }    int max(int a,int b)    {        return a>b?a:b;    }    int min(int a,int b)    {        return a<b?a:b;    }
0 0