|
| 1 | +package javacode.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +// [Problem] https://leetcode.com/problems/count-square-submatrices-with-all-ones |
| 6 | +class CountSquareSubmatrices { |
| 7 | + // Dynamic programming |
| 8 | + // O(m * n) time, O(1) space |
| 9 | + // where m = row size, n = column size |
| 10 | + public int countSquares(int[][] matrix) { |
| 11 | + int count = 0; |
| 12 | + int rowSize = matrix.length, colSize = matrix[0].length; |
| 13 | + for (int row = 0; row < rowSize; row++) { |
| 14 | + for (int col = 0; col < colSize; col++) { |
| 15 | + if (matrix[row][col] == 1 && row > 0 && col > 0) { |
| 16 | + matrix[row][col] = Math.min(matrix[row - 1][col - 1], Math.min(matrix[row - 1][col], matrix[row][col - 1])) + 1; |
| 17 | + } |
| 18 | + count += matrix[row][col]; |
| 19 | + } |
| 20 | + } |
| 21 | + return count; |
| 22 | + } |
| 23 | + |
| 24 | + // Test |
| 25 | + public static void main(String[] args) { |
| 26 | + CountSquareSubmatrices solution = new CountSquareSubmatrices(); |
| 27 | + |
| 28 | + int[][] input = { |
| 29 | + {0, 1, 1, 1}, |
| 30 | + {1, 1, 1, 1}, |
| 31 | + {0, 1, 1, 1} |
| 32 | + }; |
| 33 | + int expectedOutput = 15; |
| 34 | + int actualOutput = solution.countSquares(input); |
| 35 | + |
| 36 | + System.out.println("Test passed? " + (expectedOutput == actualOutput)); |
| 37 | + } |
| 38 | +} |
0 commit comments