Sponsored
Sponsored
The dynamic programming approach involves creating a DP array where each element represents the size of the largest square submatrix ending at that element. We'll only consider elements that are 1s, as 0s can't be part of a square of 1s. For each element that is 1, it can be the bottom-right corner of a square submatrix; we consider the minimum of the sizes of squares ending directly above, to the left, and diagonally above and to the left of it, then add 1 to this value. Sum up all the values in the DP array to get the total count of square submatrices.
Time Complexity: O(m * n), where m and n are the number of rows and columns in the matrix, respectively.
Space Complexity: O(m * n), due to the auxiliary DP matrix used to store maximum square sizes at each point.
1#include <stdio.h>
2#include <string.h>
3
4int countSquares(int** matrix, int matrixSize, int* matrixColSize) {
5
This C function calculates the number of square submatrices with all ones by using a dynamic programming matrix (dp). For each 1 in the input matrix, it calculates the maximum size of the square submatrix ending at that cell and increments the total count. Bound checks for the first row and column simplify initialization.