|
| 1 | +# Maximal Square |
| 2 | + |
| 3 | +Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. |
| 4 | + |
| 5 | +## Examples |
| 6 | + |
| 7 | +```text |
| 8 | +matrix = [ |
| 9 | + [0, 0, 1, 0, 0], |
| 10 | + [1, 1, 1, 0, 1], |
| 11 | + [0, 1, 1, 0, 0] |
| 12 | +] |
| 13 | +
|
| 14 | +Output: 4 |
| 15 | +``` |
| 16 | + |
| 17 | +## Solution |
| 18 | + |
| 19 | +The solution uses bottom-up dynamic programming to solve the problem. The solution is based on the observation that the |
| 20 | +size of the largest square ending (bottom-right corner) at a particular cell is equal to the minimum of the sizes of the |
| 21 | +largest squares ending at the three adjacent cells plus 1. |
| 22 | + |
| 23 | +We create a 2D integer array dp of size (r + 1) x (c + 1) where r is the number of rows in the input array and c is the |
| 24 | +size of each row. dp[i][j] stores the side length of the largest square ending at the cell matrix[i - 1][j - 1]. All |
| 25 | +elements of dp are initialized to 0. |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +We then use a nested loop to iterate over the input array. For each cell matrix[i - 1][j - 1], we check if the cell |
| 30 | +contains a 1. If it does, we update dp[i][j] to the minimum of the sizes of the largest squares ending at the three |
| 31 | +adjacent cells plus 1. We also update a variable max_side to store the maximum side length of the largest square we |
| 32 | +have found so far. |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | +At the end of the loop, max_side contains the side length of the largest square containing only 1's in the input array. |
| 42 | +The area of the square is max_side * max_side. |
| 43 | + |
| 44 | +### Complexity analysis |
| 45 | + |
| 46 | +#### Time Complexity |
| 47 | + |
| 48 | +O(m * n) where m is the number of rows and n is the number of columns in the input array. We iterate over each cell once, |
| 49 | +and for each cell, we perform a constant amount of work. |
| 50 | + |
| 51 | +#### Space Complexity |
| 52 | + |
| 53 | +O(m * n) where m is the number of rows and n is the number of columns. We use a 2D array dp of size (m + 1) x (n + 1) to |
| 54 | +store the side length of the largest square ending at each cell. |
0 commit comments