Counting Square Submatrices with All Ones using DP

📅 October 22, 2025 🧩 Problem Solved: 🔹 Count Square Submatrices with All Ones | Array · Dynamic Programming · Medium Core Idea: We aim to count all square submatrices that contain only 1s. This can be efficiently done using a bottom-up DP approach, where each cell in the DP table represents the size of the largest square ending at that position. Approach: Create an m × n DP array initialized with zeros. For each cell (i, j) in the matrix: If matrix[i][j] == 1, then dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) his ensures that a cell contributes to a larger square only if all three neighboring squares can form a smaller one. Add dp[i][j] to the result since it represents all possible squares ending at that cell. Edge cells (first row and first column) are directly taken from the input matrix since they can only form 1×1 squares. Complexity: ⏱️ Time: O(M × N) 📦 Space: O(M × N) (or O(N) with optimization) https://lnkd.in/dJ5VcnTN 💡 Key Takeaways: The value at each DP cell is not just 0 or 1 — it represents the number of distinct squares ending there. Always think of DP[i][j] as an answer to a sub-question — here, “What’s the largest square ending at (i, j)?” This problem shows how 2D prefix relationships can simplify submatrix counting drastically. #LeetCode #100DaysOfCode #DSA #CodingJourney #Cplusplus #ProblemSolving #DynamicProgramming #TechPrep #Arrays

  • text

To view or add a comment, sign in

Explore content categories