Problem Description
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.
Key Insights
- Use dynamic programming to build a solution where each cell in the DP table represents the side length of the largest square ending at that cell.
- If the current cell is '1', its DP value is the minimum of the top, left, and top-left neighbors plus one.
- Update a global maximum side length during the process to determine the area.
- The square's area is the square of its maximum side length.
Space and Time Complexity
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. Space Complexity: O(m * n) for the DP table (this can be optimized to O(n) with space reduction techniques).
Solution
We use a two-dimensional dynamic programming approach. We define a DP matrix with one extra row and column to simplify boundary conditions. For each cell (i, j) in the input matrix, if the value is '1', then we calculate the DP value as the minimum of its top, left, and top-left neighboring DP values plus one. This value represents the side length of the square ending at (i, j). We also keep track of the maximum side length found and finally compute the area of the maximal square by squaring the maximum side length.