Count Every All-One Square in a Binary Matrix

Quick Overview

Count Every All-One Square in a Binary Matrix. Return the number of contiguous square submatrices of matrix whose entries are all1.

Count Every All-One Square in a Binary Matrix

Company: DevRev

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Return the number of contiguous square submatrices of matrix whose entries are all 1. Count different positions and different side lengths separately. ```cpp class Solution { public: int countSquares(vector<vector<int>>& matrix); }; ``` ### Examples **Example 1:** ```text Input: matrix = [[1,1],[1,1]] Output: 5 Explanation: Four1-by-1 squares and one2-by-2 square are all ones. ``` **Example 2:** ```text Input: matrix = [[1,0,1]] Output: 2 Explanation: Only the two individual1 cells are qualifying squares. ``` ### Constraints - Each matrix dimension is between 1 and 300. - Every entry is 0 or 1. ### Contract considerations Count every qualifying position and side length separately. A nonsquare rectangular submatrix is not counted. ```hint Read the boundary condition Are different positions and side lengths counted separately, and do rectangular regions qualify? ``` ### Boundary reminders Count every qualifying position and side length separately. A nonsquare rectangular submatrix is not counted.

Overview: Count Every All-One Square in a Binary Matrix. Return the number of contiguous square submatrices of matrix whose entries are all1.

DevRev logo
DevRev
Source window: 0–3 months · as of Oct 21, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the number of contiguous square submatrices of matrix whose entries are all 1. Count different positions and different side lengths separately.

class Solution {
public:
    int countSquares(vector<vector<int>>& matrix);
};

Examples

Example 1:

Input: matrix = [[1,1],[1,1]]
Output: 5
Explanation: Four1-by-1 squares and one2-by-2 square are all ones.

Example 2:

Input: matrix = [[1,0,1]]
Output: 2
Explanation: Only the two individual1 cells are qualifying squares.

Constraints

  • Each matrix dimension is between 1 and 300.
  • Every entry is 0 or 1.

Contract considerations

Count every qualifying position and side length separately. A nonsquare rectangular submatrix is not counted.

Boundary reminders

Count every qualifying position and side length separately. A nonsquare rectangular submatrix is not counted.