문제 설명

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

Note: A leaf is a node with no children.

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

문제풀이

Matrix DP 기본문제 응용하기 쉬우니 기초를 탄탄히 ( 필터링 )


class Solution {
    func countSquares(_ matrix: [[Int]]) -> Int {
        
        var matrix = matrix
        let m = matrix.count
        let n = matrix[0].count
        var count = 0
        
        (0..<n).forEach { count += matrix[0][$0] }
        (1..<m).forEach { count += matrix[$0][0] }
        
        for y in (1..<m) {
            for x in (1..<n) {
                if matrix[y][x] == 1 {
                    matrix[y][x] = min(min(matrix[y][x-1], matrix[y-1][x]), matrix[y-1][x-1]) + 1
                    count += matrix[y][x]
                }
            }
        }
        
        return count
    }
    
}

참고 : https://leetcode.com/problems/count-square-submatrices-with-all-ones/