|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# 1277. Count Square Submatrices with All Ones |
| 4 | +# Medium |
| 5 | +# https://leetcode.com/problems/count-square-submatrices-with-all-ones |
| 6 | + |
| 7 | +=begin |
| 8 | +Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. |
| 9 | +
|
| 10 | +Example 1: |
| 11 | +Input: matrix = |
| 12 | +[ |
| 13 | + [0,1,1,1], |
| 14 | + [1,1,1,1], |
| 15 | + [0,1,1,1] |
| 16 | +] |
| 17 | +Output: 15 |
| 18 | +Explanation: |
| 19 | +There are 10 squares of side 1. |
| 20 | +There are 4 squares of side 2. |
| 21 | +There is 1 square of side 3. |
| 22 | +Total number of squares = 10 + 4 + 1 = 15. |
| 23 | +
|
| 24 | +Example 2: |
| 25 | +Input: matrix = |
| 26 | +[ |
| 27 | + [1,0,1], |
| 28 | + [1,1,0], |
| 29 | + [1,1,0] |
| 30 | +] |
| 31 | +Output: 7 |
| 32 | +Explanation: |
| 33 | +There are 6 squares of side 1. |
| 34 | +There is 1 square of side 2. |
| 35 | +Total number of squares = 6 + 1 = 7. |
| 36 | +
|
| 37 | +Constraints: |
| 38 | +* 1 <= matrix.length <= 300 |
| 39 | +* 1 <= matrix[0].length <= 300 |
| 40 | +* 0 <= matrix[i][j] <= 1 |
| 41 | +=end |
| 42 | + |
| 43 | +# @param {Integer[][]} matrix |
| 44 | +# @return {Integer} |
| 45 | +def count_squares(matrix) |
| 46 | + m, n = matrix.length, matrix[0].length |
| 47 | + result = 0 |
| 48 | + (0...m).each { |i| |
| 49 | + (0...n).each { |j| |
| 50 | + if matrix[i][j] != 0 && i > 0 && j > 0 |
| 51 | + matrix[i][j] = 1 + [matrix[i - 1][j], matrix[i - 1][j - 1], matrix[i][j - 1]].min |
| 52 | + end |
| 53 | + result += matrix[i][j] |
| 54 | + } |
| 55 | + } |
| 56 | + result |
| 57 | +end |
| 58 | + |
| 59 | +# **************** # |
| 60 | +# TEST # |
| 61 | +# **************** # |
| 62 | + |
| 63 | +require "test/unit" |
| 64 | +class Test_count_squares < Test::Unit::TestCase |
| 65 | + def test_ |
| 66 | + assert_equal 15, count_squares([[0, 1, 1, 1], [1, 1, 1, 1], [0, 1, 1, 1]]) |
| 67 | + assert_equal 7, count_squares([[1, 0, 1], [1, 1, 0], [1, 1, 0]]) |
| 68 | + end |
| 69 | +end |
0 commit comments