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.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

 

class Solution {
    public int maximalSquare(char[][] matrix) {
      if(matrix == null || matrix.length == 0) return 0;
      
      int m = matrix.length;
      int n = matrix[0].length;
      
      int result = 0;
      
      int[][] newMatrix = new int[m + 1][n + 1]; // m + 1, n + 1 
      
      for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
          if(matrix[i-1][j-1] == '1'){ // math.min can take only two inputs
            newMatrix[i][j] = Math.min(Math.min(newMatrix[i-1][j], newMatrix[i][j-1]),newMatrix[i-1][j-1] ) + 1;
            result = Math.max(result,newMatrix[i][j]);
          }
        }
      }
      return result * result;   // area, not length     
    }
}                
                     
  • Time complexity : O(mn) Single pass.

  • Space complexity : O(mn) Another matrix of same size is used for dp.

  • better space complexity is to use only one row to 

    •  O(n). Another array which stores elements in a row is used for dp.

    • public class Solution {
          public int maximalSquare(char[][] matrix) {
              int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
              int[] dp = new int[cols + 1];
              int maxsqlen = 0, prev = 0;
              for (int i = 1; i <= rows; i++) {
                  for (int j = 1; j <= cols; j++) {
                      int temp = dp[j];
                      if (matrix[i - 1][j - 1] == '1') {
                          dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
                          maxsqlen = Math.max(maxsqlen, dp[j]);
                      } else {
                          dp[j] = 0;
                      }
                      prev = temp;
                  }
              }
              return maxsqlen * maxsqlen;
          }
      }
      Complexity Analysis
      
      Time complexity : O(mn). Single pass.
      
      Space complexity : O(n). Another array which stores elements in a row is used for dp.

       

       

posted on 2018-08-11 03:32  猪猪&#128055;  阅读(107)  评论(0)    收藏  举报

导航