Skip to main content
Back to problems
Leetcode
Medium
Matrices
Arrays
Dynamic Programming
Google
Meta
Microsoft
Count Square Submatrices With All Ones

Count how many square submatrices in a binary matrix contain only 1s.

Acceptance 100%
Problem Statement

Problem

Given an m×nm \times n binary matrix, count the total number of square submatrices whose cells are all 1.

A square submatrix is a contiguous submatrix with equal height and width. Every square of every valid size should be counted separately.

Return the total count of such square submatrices.

Intuition

You need to count all-ones squares of size 1×11 \times 1, 2×22 \times 2, 3×33 \times 3, and so on, anywhere in the matrix.

Input Format

  • A binary matrix matrix of size m x n, where each cell is 0 or 1.

Output Format

  • Return an integer: the number of square submatrices consisting entirely of 1s.

Constraints

  • 1 <= m, n <= 300
  • matrix[i][j] is either 0 or 1

Hints

  • Think about the largest all-ones square that can end at each cell.
  • If a cell is 1, its contribution depends on the neighboring subproblems above, left, and diagonally above-left.

Input Format

  • matrix: a 2D integer array containing only 0 and 1.

Output Format

  • Return the total number of all-ones square submatrices.

Constraints

  • The matrix contains only binary values.
  • The answer fits in a 32-bit signed integer for typical interview constraints.
Examples
Sample cases returned by the problem API.

Example 1

Input

matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]

Output

15

Explanation

There are 10 squares of size 1x1, 4 squares of size 2x2, and 1 square of size 3x3, for a total of 15.

Example 2

Input

matrix = [[1,0,1],[1,1,0],[1,1,0]]

Output

7

Explanation

Count all square submatrices with only 1s. The total is 7.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.