From 89156f1e3ed729ada249e5d2605e3685dc1ebf14 Mon Sep 17 00:00:00 2001 From: chayan das Date: Wed, 20 Aug 2025 19:48:44 +0530 Subject: [PATCH] Create 1277. Count Square Submatrices with All Ones --- 1277. Count Square Submatrices with All Ones | 30 ++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 1277. Count Square Submatrices with All Ones diff --git a/1277. Count Square Submatrices with All Ones b/1277. Count Square Submatrices with All Ones new file mode 100644 index 0000000..47ebc4a --- /dev/null +++ b/1277. Count Square Submatrices with All Ones @@ -0,0 +1,30 @@ +class Solution { +public: + int countSquares(vector>& matrix) { + int rows = matrix.size(); + int cols = matrix[0].size(); + std::vector> dp(rows, std::vector(cols, 0)); + int cnt = 0; + for (int j = 0; j < cols; j++){ + if (matrix[0][j] == 1){ + dp[0][j] = 1; + cnt += dp[0][j]; + } + } + for (int i = 1; i < rows; i++){ + if (matrix[i][0] == 1){ + dp[i][0] = 1; + cnt += dp[i][0]; + } + } + for (int i = 1; i < rows; i++){ + for (int j = 1; j < cols; j++){ + if (matrix[i][j] == 1){ + dp[i][j] = std::min({dp[i-1][j], dp[i-1][j-1], dp[i][j-1]}) + 1; + cnt += dp[i][j]; + } + } + } + return cnt; + } +};