• 27.8%

https://leetcode.com/problems/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.

https://discuss.leetcode.com/topic/15328/easy-dp-solution-in-c-with-detailed-explanations-8ms-o-n-2-time-and-o-n-space

Easy DP solution in C++ with detailed explanations (8ms, O(n^2) time and O(n) space)

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.

1. P[0][j] = matrix[0][j] (topmost row);
2. P[i][0] = matrix[i][0] (leftmost column);
3. 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.

Putting them into codes, and maintain a variable maxsize to record the maximum size of the square we have seen, we have the following (unoptimized) solution.

Now let’s try to optimize the above solution. As can be seen, each time when we update size[i][j], we only need size[i][j - 1], size[i - 1][j - 1] (at the previous left column) and size[i - 1][j] (at the current column). So we do not need to maintain the full m*n matrix. In fact, keeping two columns is enough. Now we have the following optimized solution.

Now you see the solution is finished? In fact, it can still be optimized! In fact, we need not maintain two vectors and one is enough. If you want to explore this idea, please refer to the answers provided by @stellari below. Moreover, in the code above, we distinguish between the 0-th row and other rows since the 0-th row has no row above it. In fact, we can make all the m rows the same by padding a 0 row on the top (in the following code, we pad a 0 on top of dp). Finally, we will have the following short code :) If you find it hard to understand, try to run it using your pen and paper and notice how it realizes what the two-vector solution does using only one vector.

This solution, since posted, has been suggested various improvements by kind people. For a more comprehensive collection of the solutions, please visit my technical blog.

https://discuss.leetcode.com/topic/22185/clear-c-solution-no-extra-space-12-ms

Clear C++ solution, no extra space, 12 ms.

A square with ‘1’ means any ‘0’ will interrupt counting of it’s right/down/right-down, and ‘1’ will ‘inherit’ the existing counting result.

Sine the target is a square, we shall take the smallest counting result from up/left/up-left.

So for each element ‘0’, it doesn’t inherit previous accumulated counting;

And for each element ‘1’, it takes the smallest number from left/up/left-up and add 1 to it

https://discuss.leetcode.com/topic/29332/20-lines-c-solution-using-dynamic-programming

20 lines C++ solution using dynamic programming

https://discuss.leetcode.com/topic/15373/6-lines-visual-explanation-o-mn

6 lines, Visual Explanation, O(mn)

Explanation

What’s the largest (full-of-ones-)square ending at (i,j), meaning lower right corner in row i, column j? Imagine there are 4x4 squares above, above-left and left of it:

Clearly, if cell (i,j) itself is 1 as well, then there’s a 5x5 square ending at (i,j). And if there were 5x5 squares above, above-left and left of it, then we’d have a 6x6. So to find the largest square ending at (i,j), we just take the minimum size of squares ending at (i-1,j), (i-1,j-1) and (i,j-1), and add 1.

Implementation - 164 ms

I write the maximum sizes directly into the input matrix A. Cell A[i][j] will tell the side length of the largest square ending at (i,j). I go top to bottom and left to right, so (i-1,j), (i-1,j-1) and (i,j-1) have all been handled already. First thing I do for each cell is turn it into an integer, and then if it’s 1 and it’s not on the top or left border of the matrix, I determine its largest-square size as explained above. In the end, I return 0 for the empty matrix and otherwise the area of the largest square ending anywhere.

Smaller Version - 132 ms

This version is a bit smaller and faster due to using more of Python and some “tricks”:

O(n) Extra Space - 128 ms

Here’s a version that doesn’t overwrite the input matrix but uses two integer lists: s tells the sizes of the squares ending it the current row and p does the same for the previous row.

Note that in Python with its integer and string objects, I’m not sure this actually saves space. But in other languages, overwriting the input array might not even be possible, and if it’s possible, it might take more space than a “O(n) Extra Space” variant.

https://discuss.leetcode.com/topic/15381/my-c-code-8ms-dp-o-n-2-time-o-n-space

My C++ code, 8ms (DP, O(n^2)time, O(n) space)

The basic idea is to do DP: scan the matrix row by row (top down) and colume by colume (left to right) and for the position [i][j], the maximum square with the bottom-right corner sitting at [i][j] will have the edge length of

For the case that matrix[i][j] = ‘1’, the algorithm tries to grow the square sitting at [i-1][j-1], area[i-1][j-1] by 1. However, it is also limitted by the bottom edge at row i and right edge at col j, which was represented by area[i][j-1] and area[i-1][j] repectively. We have to choose the min of those three values.

The DP table works on a ping-pong mode to save memory since the area recursive equation only relys on i and i-1 rows.

https://discuss.leetcode.com/topic/16851/share-my-concise-python-solution

Share my concise python solution