Number of square matrices with all 1s

Last Updated : 1 Aug, 2026

Given an n × m binary matrix mat[][], count the total number of square submatrices whose every element is 1.

Examples: 

Input: mat[][] = [[0, 1, 1], [1, 1, 1], [0, 1, 1]]

blobid1_1781592199

Output: 9
Explanation: There are 9 square submatrices containing only 1s:
7 squares of size 1 * 1
2 squares of size 2 * 2
0 squares of size 3 * 3
Therefore, the total number of square submatrices with all 1s is 7 + 2 = 9.

Input: mat[][] = [[1, 0, 1], [1, 1, 0],  [1, 1, 0]]

blobid0_1781592121

Output: 7
Explanation: There are 7 square submatrices containing only 1s:
6 squares of size 1 * 1
1 squares of size 2 * 2
0 squares of size 3 * 3
Therefore, the total number of square submatrices with all 1s is 6 + 1 = 7.

Try It Yourself
redirect icon

[Naive Approach] Check Every Possible Square - O(n * m * min(n, m) ^ 3) Time and O(1) Space

The idea is to consider every cell as the top-left corner of a square and try all possible square sizes. For each square, traverse all its cells and verify whether every element is 1. If yes, count it; otherwise, stop checking larger squares from that position.

C++
#include <iostream>
#include <vector>
using namespace std;

int countSquares(vector<vector<int>> &mat)
{

    int n = mat.size();
    int m = mat[0].size();

    int res = 0;

    // Consider every cell as top-left corner
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {

            int maxSize = min(n - i, m - j);

            // Try all possible square sizes
            for (int size = 1; size <= maxSize; size++)
            {

                bool valid = true;

                // Check all cells of current square
                for (int r = i; r < i + size && valid; r++)
                {
                    for (int c = j; c < j + size; c++)
                    {

                        if (mat[r][c] == 0)
                        {
                            valid = false;
                            break;
                        }
                    }
                }

                if (valid)
                {
                    res++;
                }
                else
                {
                    break;
                }
            }
        }
    }

    return res;
}

int main()
{

    int n = 3, m = 3;

    vector<vector<int>> mat = {{1, 0, 1}, {1, 1, 0}, {1, 1, 0}};

    cout << countSquares(mat);

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static int countSquares(int[][] mat)
    {
        int n = mat.length;
        int m = mat[0].length;

        int res = 0;

        // Consider every cell as top-left corner
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                int maxSize = Math.min(n - i, m - j);

                // Try all possible square sizes
                for (int size = 1; size <= maxSize;
                     size++) {

                    boolean valid = true;

                    // Check all cells of current square
                    for (int r = i; r < i + size && valid;
                         r++) {
                        for (int c = j; c < j + size; c++) {

                            if (mat[r][c] == 0) {
                                valid = false;
                                break;
                            }
                        }
                    }

                    if (valid) {
                        res++;
                    }
                    else {
                        break;
                    }
                }
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        int n = 3, m = 3;

        int[][] mat
            = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };

        System.out.println(countSquares(mat));
    }
}
Python
def countSquares(mat):

    n = len(mat)
    m = len(mat[0])

    res = 0

    # Consider every cell as top-left corner
    for i in range(n):
        for j in range(m):

            maxSize = min(n - i, m - j)

            # Try all possible square sizes
            for size in range(1, maxSize + 1):

                valid = True

                # Check all cells of current square
                for r in range(i, i + size):
                    if not valid:
                        break
                    for c in range(j, j + size):
                        if mat[r][c] == 0:
                            valid = False
                            break

                if valid:
                    res += 1
                else:
                    break

    return res

if __name__ == "__main__":

    mat = [
        [1, 0, 1],
        [1, 1, 0],
        [1, 1, 0]
    ]

    print(countSquares(mat))
C#
using System;

public class GFG {
    public static int CountSquares(int[][] mat)
    {
        int n = mat.Length;
        int m = mat[0].Length;

        int res = 0;

        // Consider every cell as top-left corner
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int maxSize = Math.Min(n - i, m - j);

                // Try all possible square sizes
                for (int size = 1; size <= maxSize;
                     size++) {
                    bool valid = true;

                    // Check all cells of current square
                    for (int r = i; r < i + size && valid;
                         r++) {
                        for (int c = j; c < j + size; c++) {
                            if (mat[r][c] == 0) {
                                valid = false;
                                break;
                            }
                        }
                    }

                    if (valid) {
                        res++;
                    }
                    else {
                        break;
                    }
                }
            }
        }

        return res;
    }

    public static void Main()
    {
        int[][] mat = { new int[] { 1, 0, 1 },
                        new int[] { 1, 1, 0 },
                        new int[] { 1, 1, 0 } };

        Console.WriteLine(CountSquares(mat));
    }
}
JavaScript
function countSquares(mat) {

    let n = mat.length;
    let m = mat[0].length;

    let res = 0;

    // Consider every cell as top-left corner
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            let maxSize = Math.min(n - i, m - j);

            // Try all possible square sizes
            for (let size = 1; size <= maxSize; size++) {

                let valid = true;

                // Check all cells of current square
                for (let r = i; r < i + size && valid; r++) {
                    for (let c = j; c < j + size; c++) {

                        if (mat[r][c] === 0) {
                            valid = false;
                            break;
                        }
                    }
                }

                if (valid) {
                    res++;
                } else {
                    break;
                }
            }
        }
    }

    return res;
}

// Driver Code
let mat = [[1, 0, 1], [1, 1, 0], [1, 1, 0]];
console.log(countSquares(mat));

Output
7

[Better Approach] Using Dynamic Programming - O(n * m) Time and O(n * m) Space

The idea is to store at each cell the size of the largest square submatrix of 1s ending at that cell. If the current cell contains 1, then its value depends on the minimum value among its top, left, and top-left neighbors. The sum of all DP values gives the total number of square submatrices containing only 1s.

C++
#include <iostream>
#include <vector>
using namespace std;

int countSquares(vector<vector<int>> &mat)
{
    int n = mat.size();
    int m = mat[0].size();

    vector<vector<int>> dp(n, vector<int>(m, 0));

    int res = 0;

    // Fill DP table
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            // First row or first column
            if (i == 0 || j == 0)
            {
                dp[i][j] = mat[i][j];
            }

            // Current cell is 1
            else if (mat[i][j] == 1)
            {
                dp[i][j] = 1 + min({
                                   dp[i - 1][j],    // Top
                                   dp[i][j - 1],    // Left
                                   dp[i - 1][j - 1] // Top-left
                               });
            }

            // Add squares ending at current cell
            res += dp[i][j];
        }
    }

    return res;
}

int main()
{
    int n = 3, m = 3;

    vector<vector<int>> mat = {{1, 0, 1}, {1, 1, 0}, {1, 1, 0}};

    cout << countSquares(mat);

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static int countSquares(int[][] mat)
    {
        int n = mat.length;
        int m = mat[0].length;

        int[][] dp = new int[n][m];

        int res = 0;

        // Fill DP table
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // First row or first column
                if (i == 0 || j == 0) {
                    dp[i][j] = mat[i][j];
                }

                // Current cell is 1
                else if (mat[i][j] == 1) {
                    dp[i][j]
                        = 1
                          + Math.min(Math.min(dp[i - 1][j],
                                              dp[i][j - 1]),
                                     dp[i - 1][j - 1]);
                }

                // Add squares ending at current cell
                res += dp[i][j];
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        int n = 3, m = 3;

        int[][] mat
            = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };

        System.out.println(countSquares(mat));
    }
}
Python
def countSquares(mat):
    n = len(mat)
    m = len(mat[0])

    dp = [[0] * m for _ in range(n)]

    res = 0

    # Fill DP table
    for i in range(n):
        for j in range(m):
            # First row or first column
            if i == 0 or j == 0:
                dp[i][j] = mat[i][j]

            # Current cell is 1
            elif mat[i][j] == 1:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i]
                                   [j - 1], dp[i - 1][j - 1])

            # Add squares ending at current cell
            res += dp[i][j]

    return res

if __name__ == "__main__":

    n, m = 3, 3

    mat = [
        [1, 0, 1],
        [1, 1, 0],
        [1, 1, 0]
    ]

    print(countSquares(mat))
C#
using System;

public class GFG {
    static int countSquares(int[][] mat)
    {
        int n = mat.Length;
        int m = mat[0].Length;

        int[][] dp = new int[n][];

        for (int i = 0; i < n; i++) {
            dp[i] = new int[m];
        }

        int res = 0;

        // Fill DP table
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // First row or first column
                if (i == 0 || j == 0) {
                    dp[i][j] = mat[i][j];
                }

                // Current cell is 1
                else if (mat[i][j] == 1) {
                    dp[i][j]
                        = 1
                          + Math.Min(Math.Min(dp[i - 1][j],
                                              dp[i][j - 1]),
                                     dp[i - 1][j - 1]);
                }

                // Add squares ending at current cell
                res += dp[i][j];
            }
        }

        return res;
    }

    static void Main()
    {
        int[][] mat = { new int[] { 1, 0, 1 },
                        new int[] { 1, 1, 0 },
                        new int[] { 1, 1, 0 } };

        Console.WriteLine(countSquares(mat));
    }
}
JavaScript
function countSquares(mat) {
    let n = mat.length;
    let m = mat[0].length;

    let dp = Array.from({ length: n }, () => Array(m).fill(0));

    let res = 0;

    // Fill DP table
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            // First row or first column
            if (i === 0 || j === 0) {
                dp[i][j] = mat[i][j];
            }

            // Current cell is 1
            else if (mat[i][j] === 1) {
                dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
            }

            // Add squares ending at current cell
            res += dp[i][j];
        }
    }

    return res;
}

// Driver Code
let n = 3, m = 3;

let mat = [[1, 0, 1], [1, 1, 0], [1, 1, 0]];

console.log(countSquares(mat));

Output
7

[Expected Approach] Dynamic Programming with In-Place Matrix Update - O(n * m) Time and O(1) Space

The idea is to store at each cell the size of the largest square submatrix of 1s ending at that cell. This size depends on the minimum value among its top, left, and top-left neighbors. Summing these values gives the total number of square submatrices containing only 1s.

Let us understand with example:
Input: n = 3, m = 3 mat[][] = [[1, 0, 1], [1, 1, 0],  [1, 1, 0]]

  • Start with mat = [[1, 0, 1], [1, 1, 0], [1, 1, 0]] and res = 0.
  • While processing the first row and first column, the cells containing 1 contribute four 1 × 1 squares, so res = 4.
  • At cell (1, 1), update mat[1][1] = 1 + min(0, 1, 1) = 1; add it to res, so res = 5.
  • At cell (2, 1), update mat[2][1] = 1 + min(1, 1, 1) = 2; add it to res, so res = 7.
  • The remaining cells contain 0, so they do not contribute any squares. Hence, the total number of square submatrices with all 1s is 7.
C++
#include <iostream>
#include <vector>
using namespace std;

int countSquares(vector<vector<int>> &mat)
{

    int res = 0;
    int n = mat.size();
    int m = mat[0].size();

    // Traverse matrix row by row
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {

            // Cell containing 0 cannot form a square
            if (mat[i][j] == 0)
            {
                continue;
            }

            // Update square size using neighbors
            if (i > 0 && j > 0)
            {

                mat[i][j] += min({
                    mat[i - 1][j],    // Top
                    mat[i][j - 1],    // Left
                    mat[i - 1][j - 1] // Top-left
                });
            }

            // Add number of squares ending here
            res += mat[i][j];
        }
    }

    return res;
}

int main()
{
    int n = 3, m = 3;

    vector<vector<int>> mat = {{1, 0, 1}, {1, 1, 0}, {1, 1, 0}};

    cout << countSquares(mat);

    return 0;
}
Java
import java.util.Arrays;

public class GFG {
    public static int countSquares(int[][] mat)
    {
        int res = 0;
        int n = mat.length;
        int m = mat[0].length;

        // Traverse matrix row by row
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // Cell containing 0 cannot form a square
                if (mat[i][j] == 0) {
                    continue;
                }

                // Update square size using neighbors
                if (i > 0 && j > 0) {
                    mat[i][j]
                        += Math.min(Math.min(mat[i - 1][j],
                                             mat[i][j - 1]),
                                    mat[i - 1][j - 1]);
                }

                // Add number of squares ending here
                res += mat[i][j];
            }
        }

        return res;
    }

    public static void main(String[] args)
    {
        int[][] mat
            = { { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 0 } };
        System.out.println(countSquares(mat));
    }
}
Python
def countSquares(mat):
    res = 0
    n = len(mat)
    m = len(mat[0])

    # Traverse matrix row by row
    for i in range(n):
        for j in range(m):

            # Cell containing 0 cannot form a square
            if mat[i][j] == 0:
                continue

            # Update square size using neighbors
            if i > 0 and j > 0:
                mat[i][j] += min(mat[i - 1][j], mat[i]
                                 [j - 1], mat[i - 1][j - 1])

            # Add number of squares ending here
            res += mat[i][j]

    return res

if __name__ == "__main__":

    n, m = 3, 3

    mat = [
        [1, 0, 1],
        [1, 1, 0],
        [1, 1, 0]
    ]

    print(countSquares(mat))
C#
using System;

public class GFG {
    static int countSquares(int[][] mat)
    {
        int res = 0;
        int n = mat.Length;
        int m = mat[0].Length;

        // Traverse matrix row by row
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // Cell containing 0 cannot form a square
                if (mat[i][j] == 0) {
                    continue;
                }

                // Update square size using neighbors
                if (i > 0 && j > 0) {
                    mat[i][j]
                        += Math.Min(Math.Min(mat[i - 1][j],
                                             mat[i][j - 1]),
                                    mat[i - 1][j - 1]);
                }

                // Add number of squares ending here
                res += mat[i][j];
            }
        }

        return res;
    }

    static void Main()
    {
        int[][] mat = new int[][] { new int[] { 1, 0, 1 },
                                    new int[] { 1, 1, 0 },
                                    new int[] { 1, 1, 0 } };
        Console.WriteLine(countSquares(mat));
    }
}
JavaScript
function countSquares(mat) {
    let res = 0;
    let n = mat.length;
    let m = mat[0].length;

    // Traverse matrix row by row
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // Cell containing 0 cannot form a square
            if (mat[i][j] === 0) {
                continue;
            }

            // Update square size using neighbors
            if (i > 0 && j > 0) {
                mat[i][j] += Math.min(mat[i - 1][j], mat[i][j - 1], mat[i - 1][j - 1]);
            }

            // Add number of squares ending here
            res += mat[i][j];
        }
    }

    return res;
}

// Driver Code
let mat = [[1, 0, 1], [1, 1, 0], [1, 1, 0]];
console.log(countSquares(mat));

Output
7
Comment