Problem 1277

Abstract / Summary

Count all square submatrices filled with ones in a given matrix of zeros and ones.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1277.py

class Solution:
    def countSquares(self, matrix: List[List[int]]) -> int:
        width  = len(matrix[0])
        height = len(matrix)

        # 1x1 in first row
        result = sum(matrix[0])
        for y in range(1, height):
            # 1x1 in first column
            result += matrix[y][0]
            # everything else
            for x in range(1, width):
                # smallest square on top/left/topleft side
                a = matrix[y - 1][x - 1]
                b = matrix[y - 1][x    ]
                c = matrix[y    ][x - 1]
                # grow it by one
                count = 1 + min(a, b, c)
                # little trick: stays zero or becomes the lowest of a,b,c
                matrix[y][x] *= count

                # count all of them
                result += matrix[y][x]

        return result
25 lines | 861 bytes | submitted January 8, 2024 | GitHub   46% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The countSquares method receives a binary matrix and returns the total number of square sub-matrices that consist entirely of 1s. It walks through the matrix once, building on previously computed information to determine how large a square can end at each cell. The result is accumulated incrementally, so the final return value represents the sum of all possible squares of every size.

Key Steps

The first part of the method extracts the dimensions of the input matrix. By storing the width and height in local variables, the code avoids repeated attribute lookups during the nested loops.

width  = len(matrix[0])
height = len(matrix)

The algorithm begins by counting the trivial 1x1 squares that appear in the first row. Because each 1 in that row forms a square of size one, the sum of the row directly contributes to the final count.

result = sum(matrix[0])

The outer loop iterates over the remaining rows, starting at index 1. For each new row, the element in the first column is treated as a standalone 1x1 square, and its value is added to the running total.

for y in range(1, height):
    result += matrix[y][0]

Inside the same outer loop, an inner loop processes the rest of the columns, also starting at index 1. For each cell (y, x), the algorithm looks at three neighboring cells that form the top, left, and top-left corners of a potential larger square:

a = matrix[y - 1][x - 1]   # top-left
b = matrix[y - 1][x]       # top
c = matrix[y][x - 1]       # left

The size of the largest square that can end at (y, x) is one plus the smallest of those three values. This works because a square can be extended only if all three neighboring squares are at least as large as the new size.

count = 1 + min(a, b, c)

A compact trick updates the original matrix cell in place. Multiplying the original binary value (0 or 1) by the computed count yields 0 when the cell is 0, preserving the fact that no square can end there, and yields the correct size when the cell is 1.

matrix[y][x] *= count

Finally, the updated cell value-now representing the number of squares that end at that position-is added to the cumulative result.

result += matrix[y][x]

After all rows and columns have been processed, the method returns the accumulated total.

return result

Edge Cases Handled

When the matrix consists of a single row, the outer loop is skipped entirely, and the result is simply the sum of that row, correctly counting each 1 as a 1x1 square. Similarly, for a single column, the inner loop does not execute, and each 1 in the column is added during the outer loop’s first-column handling, again yielding the correct count.

If the matrix contains only 0s, the initial sum of the first row is zero, and every subsequent addition encounters a zero in the first column or a zero multiplied by any count, leaving the result unchanged at zero. This correctly reflects the absence of any all-1 squares.

When the matrix is filled entirely with 1s, the dynamic programming step propagates increasing counts across the grid. Each cell accumulates the size of the largest square that can end there, and the result aggregates the contributions of all possible squares, from size 1x1 up to the maximal square that fits in the matrix.

The algorithm also gracefully handles rectangular matrices where width and height differ. The nested loops respect the actual dimensions, and the three neighbor accesses are always within bounds because the loops start at index 1.

Performance Optimizations

The implementation performs the computation in a single pass over the matrix, avoiding any secondary data structures. By reusing the input matrix to store intermediate square sizes, it eliminates the need for an auxiliary DP array, thereby reducing memory pressure.

The multiplication trick (matrix[y][x] *= count) serves two purposes: it preserves the zero-value cells without extra conditional checks, and it directly writes the computed size back into the matrix, saving an assignment step. This in-place update also ensures that subsequent cells can read the already-computed sizes without additional lookups.

Using min(a, b, c) to determine the limiting neighbor is a constant-time operation that captures the essential constraint for square growth. Because the algorithm only accesses three neighboring cells per iteration, cache locality is high, and the inner loop runs with minimal overhead.

Accumulating the result incrementally avoids a second pass to sum the DP values after the matrix has been processed. Each cell contributes to the final answer as soon as its size is known, which streamlines the overall flow and keeps the runtime tight.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big square grid made of many tiny boxes, where some boxes have a one inside and some have a zero. Think of the ones as special tiles that help build a larger shape. This code is like a curious little explorer walking through every single box of that grid to find every hidden square shape that can be made.

First, the code measures how wide and tall the grid is so it knows exactly where it can look. It starts at the very top row and counts up all the ones it can see. Then, it starts moving row by row, scanning each square one by one.

When the explorer stands on a tile that has a one, it looks back at the three neighbors right next to it: the one directly above, the one directly to the left, and the one diagonal to the top-left. By checking those three neighbors, the code figures out how big of a square can be built with the current tile as the bottom-right corner. It takes the smallest number of layers from those neighbors and adds one to grow the square.

The code keeps a running total of all these squares it discovers. It updates the grid as it goes, turning those ones into bigger numbers that represent how many square sizes occupy that spot. By the time it finishes walking through the whole grid, it has collected a total count of every single square that was hiding in plain sight.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.38 | σ = 0.96

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java C# Go Rust TS
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
Garvit244 Python
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
Garvit244 Python
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
withaarzoo C++
37 links | 22 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   January 8, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality