zoukankan      html  css  js  c++  java
  • [LeetCode 1277] Count Square Submatrices with All Ones

    Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

     

    Example 1:

    Input: matrix =
    [
      [0,1,1,1],
      [1,1,1,1],
      [0,1,1,1]
    ]
    Output: 15
    Explanation: 
    There are 10 squares of side 1.
    There are 4 squares of side 2.
    There is  1 square of side 3.
    Total number of squares = 10 + 4 + 1 = 15.
    

    Example 2:

    Input: matrix = 
    [
      [1,0,1],
      [1,1,0],
      [1,1,0]
    ]
    Output: 7
    Explanation: 
    There are 6 squares of side 1.  
    There is 1 square of side 2. 
    Total number of squares = 6 + 1 = 7.
    

     

    Constraints:

    • 1 <= arr.length <= 300
    • 1 <= arr[0].length <= 300
    • 0 <= arr[i][j] <= 1

    The brute force solution of using each cell as the top left corner and check all possible square submatrices has runtime of O(N^3) * O(N^2), which is too slow. 

    O(N^2) dynamic programming solution

    The final answer is the sum of the number of square submatrices at cell (i, j) over all cells. So let's define dp[i][j] as the maximum side length of the square submatrix whose bottom right corner is cell (i, j). The maximum side length also equals to the number of square submatrices with bottom right corner at cell (i, j). So dp[i][j] is also the number of square submatrices whose bottom right corner is cell (i, j). 

    If cell (i, j) is 0, then dp[i][j] is 0; Otherwise, to compute dp[i][j], we need to take the minimum side length of dp[i - 1][j], dp[i][j - 1] and dp[i - 1][j - 1] and add 1 to this min. 

    class Solution {
        public int countSquares(int[][] matrix) {
            int m = matrix.length, n = matrix[0].length, cnt = 0;  
            //dp[i][j]: the number of square submatrices whose bottom right corner is cell (i, j)
            //also the maximum side length of the square submatrix whose bottom right corner is cell (i, j)
            int[][] dp = new int[m][n];
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(matrix[i][j] == 1 && i > 0 && j > 0) {
                        dp[i][j] = 1 + Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]),dp[i - 1][j - 1]);
                    }
                    else {
                        dp[i][j] = matrix[i][j];
                    }
                    cnt += dp[i][j];
                }
            }
            return cnt;
        }
    }

      

    Related Problems

    [LeetCode 1504] Count Submatrices With All Ones

  • 相关阅读:
    简单的纯css菜单
    提高 web 应用性能之 JavaScript 性能调优(转)
    从拖延者到行动派的10个秘诀(转)
    程序员,你应该知道(转)
    幽默的经济学+组织领导学
    [SQL基础]统计信息解释
    演讲集合
    最隐晦的程序设计指引(转)
    windows 7 "unmountable boot volume" 解决方法
    kafka与springboot集成2
  • 原文地址:https://www.cnblogs.com/lz87/p/14395076.html
Copyright © 2011-2022 走看看