[LeetCode] 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.

Thought process:
Dynamic programming:
  1. Sub-problem: find the length of the largest square whose bottom-right corner is at matrix[i][j].
  2. Formula: 
    1. To get a square of length 2, all top-left, top, and left neighbors of matrix[i][j] must have a square of length 1.
    2. To get a square of length 3, all top-left, top, and left neighbors of matrix[i][j] must have a square of length 2.
    3. ...
    4. f[i][j] = min(f[i - 1][j - 1], f[i - 1][j], f[i][j - 1]) + 1.
  3. Initialization: 
    1. f[i][0] = 1 if matrix[i][0] = 1. Otherwise 0.
    2. f[0][i] = 1 if matrix[0][i] = 1. Otherwise 0.
  4. Answer: the square of the max of f[i][j].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int height = matrix.length;
        int width = matrix[0].length;
        int[][] f = new int[height][width];
        int max = 0;
        
        for (int i = 0; i < height; i++) {
            f[i][0] = matrix[i][0] - '0';
            if (f[i][0] == 1) {
                max = 1;
            }
        }
        for (int i = 0; i < width; i++) {
            f[0][i] = matrix[0][i] - '0';
            if (f[0][i] == 1) {
                max = 1;
            }
        }
        
        for (int i = 1; i < height; i++) {
            for (int j = 1; j < width; j++) {
                if (matrix[i][j] == '1') {
                    f[i][j] = Math.min(f[i - 1][j - 1], Math.min(f[i - 1][j], f[i][j - 1])) + 1;
                    max = Math.max(f[i][j], max);
                }
            }
        }
        
        return max * max;
    }
}

Time complexity: O(height * width).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee