## 221. Maximal Square

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

b'
\n\n

## Summary

\n

We need to find the largest square comprising of all ones in the given matrix. In other words we need to find the largest set of connected ones in the given matrix that forms a square.

\n

## Solution

\n
\n

#### Approach #1 Brute Force [Accepted]

\n

The simplest approach consists of trying to find out every possible square of 1\xe2\x80\x99s that can be formed from within the matrix. The question now is \xe2\x80\x93 how to go for it?

\n

We use a variable to contain the size of the largest square found so far and another variable to store the size of the current, both initialized to 0. Starting from the left uppermost point in the matrix, we search for a 1. No operation needs to be done for a 0. Whenever a 1 is found, we try to find out the largest square that can be formed including that 1. For this, we move diagonally (right and downwards), i.e. we increment the row index and column index temporarily and then check whether all the elements of that row and column are 1 or not. If all the elements happen to be 1, we move diagonally further as previously. If even one element turns out to be 0, we stop this diagonal movement and update the size of the largest square. Now we, continue the traversal of the matrix from the element next to the initial 1 found, till all the elements of the matrix have been traversed.

\n

Java

\n
public class Solution {\n    public int maximalSquare(char[][] matrix) {\n        int rows = matrix.length, cols = rows > 0 ? matrix.length : 0;\n        int maxsqlen = 0;\n        for (int i = 0; i < rows; i++) {\n            for (int j = 0; j < cols; j++) {\n                if (matrix[i][j] == \'1\') {\n                    int sqlen = 1;\n                    boolean flag = true;\n                    while (sqlen + i < rows && sqlen + j < cols && flag) {\n                        for (int k = j; k <= sqlen + j; k++) {\n                            if (matrix[i + sqlen][k] == \'0\') {\n                                flag = false;\n                                break;\n                            }\n                        }\n                        for (int k = i; k <= sqlen + i; k++) {\n                            if (matrix[k][j + sqlen] == \'0\') {\n                                flag = false;\n                                break;\n                            }\n                        }\n                        if (flag)\n                            sqlen++;\n                    }\n                    if (maxsqlen < sqlen) {\n                        maxsqlen = sqlen;\n                    }\n                }\n            }\n        }\n        return maxsqlen * maxsqlen;\n    }\n}\n
\n

Complexity Analysis

\n
\n
• Time complexity : . In worst case, we need to traverse the complete matrix for every 1.
• \n
• Space complexity : . No extra space is used.
• \n
\n
\n

#### Approach #2 (Dynamic Programming) [Accepted]

\n

Algorithm

\n

We will explain this approach with the help of an example.

\n
0 1 1 1 0\n1 1 1 1 1\n0 1 1 1 1\n0 1 1 1 1\n0 0 1 1 1\n
\n

We initialize another matrix (dp) with the same dimensions as the original one initialized with all 0\xe2\x80\x99s.

\n

dp(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix.

\n

Starting from index (0,0), for every 1 found in the original matrix, we update the value of the current element as

\n

\n\n

\n

We also remember the size of the largest square found so far. In this way, we traverse the original matrix once and find out the required maximum size. This gives the side length of the square (say ). The required result is the area .

\n

To understand how this solution works, see the figure below.

\n \n

An entry 2 at implies that we have a square of side 2 up to that index in the original matrix. Similarly, a 2 at and implies that a square of side 2 exists up to that index in the original matrix. Now to make a square of side 3, only a single entry of 1 is pending at . So, we enter a 3 corresponding to that position in the dp array.

\n

Now consider the case for the index . Here, the entries at index and imply that a square of side 3 is possible up to their indices. But, the entry 1 at index indicates that a square of side 1 only can be formed up to its index. Therefore, while making an entry at the index , this element obstructs the formation of a square having a side larger than 2. Thus, the maximum sized square that can be formed up to this index is of size .

\n

Java

\n
public class Solution {\n    public int maximalSquare(char[][] matrix) {\n        int rows = matrix.length, cols = rows > 0 ? matrix.length : 0;\n        int[][] dp = new int[rows + 1][cols + 1];\n        int maxsqlen = 0;\n        for (int i = 1; i <= rows; i++) {\n            for (int j = 1; j <= cols; j++) {\n                if (matrix[i-1][j-1] == \'1\'){\n                    dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;\n                    maxsqlen = Math.max(maxsqlen, dp[i][j]);\n                }\n            }\n        }\n        return maxsqlen * maxsqlen;\n    }\n}\n
\n

Complexity Analysis

\n
\n
• \n

Time complexity : . Single pass.

\n
• \n
• \n

Space complexity : . Another matrix of same size is used for dp.

\n
• \n
\n
\n

#### Approach #3 (Better Dynamic Programming) [Accepted]

\n

Algorithm

\n

In the previous approach for calculating dp of row we are using only the previous element and the row. Therefore, we don\'t need 2D dp matrix as 1D dp array will be sufficient for this.

\n

Initially the dp array contains all 0\'s. As we scan the elements of the original matrix across a row, we keep on updating the dp array as per the equation , where prev refers to the old . For every row, we repeat the same process and update in the same dp array.

\n \n

java

\n
public class Solution {\n    public int maximalSquare(char[][] matrix) {\n        int rows = matrix.length, cols = rows > 0 ? matrix.length : 0;\n        int[] dp = new int[cols + 1];\n        int maxsqlen = 0, prev = 0;\n        for (int i = 1; i <= rows; i++) {\n            for (int j = 1; j <= cols; j++) {\n                int temp = dp[j];\n                if (matrix[i - 1][j - 1] == \'1\') {\n                    dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;\n                    maxsqlen = Math.max(maxsqlen, dp[j]);\n                } else {\n                    dp[j] = 0;\n                }\n                prev = temp;\n            }\n        }\n        return maxsqlen * maxsqlen;\n    }\n}\n
\n

Complexity Analysis

\n
\n
• \n

Time complexity : . Single pass.

\n
• \n
• \n

Space complexity : . Another array which stores elements in a row is used for dp.

\n
• \n
\n

Analysis written by: @vinod23

\n
'