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.
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.
[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>usingnamespacestd;intcountSquares(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();intres=0;// Consider every cell as top-left cornerfor(inti=0;i<n;i++){for(intj=0;j<m;j++){intmaxSize=min(n-i,m-j);// Try all possible square sizesfor(intsize=1;size<=maxSize;size++){boolvalid=true;// Check all cells of current squarefor(intr=i;r<i+size&&valid;r++){for(intc=j;c<j+size;c++){if(mat[r][c]==0){valid=false;break;}}}if(valid){res++;}else{break;}}}}returnres;}intmain(){intn=3,m=3;vector<vector<int>>mat={{1,0,1},{1,1,0},{1,1,0}};cout<<countSquares(mat);return0;}
Java
importjava.util.Arrays;publicclassGFG{publicstaticintcountSquares(int[][]mat){intn=mat.length;intm=mat[0].length;intres=0;// Consider every cell as top-left cornerfor(inti=0;i<n;i++){for(intj=0;j<m;j++){intmaxSize=Math.min(n-i,m-j);// Try all possible square sizesfor(intsize=1;size<=maxSize;size++){booleanvalid=true;// Check all cells of current squarefor(intr=i;r<i+size&&valid;r++){for(intc=j;c<j+size;c++){if(mat[r][c]==0){valid=false;break;}}}if(valid){res++;}else{break;}}}}returnres;}publicstaticvoidmain(String[]args){intn=3,m=3;int[][]mat={{1,0,1},{1,1,0},{1,1,0}};System.out.println(countSquares(mat));}}
Python
defcountSquares(mat):n=len(mat)m=len(mat[0])res=0# Consider every cell as top-left cornerforiinrange(n):forjinrange(m):maxSize=min(n-i,m-j)# Try all possible square sizesforsizeinrange(1,maxSize+1):valid=True# Check all cells of current squareforrinrange(i,i+size):ifnotvalid:breakforcinrange(j,j+size):ifmat[r][c]==0:valid=Falsebreakifvalid:res+=1else:breakreturnresif__name__=="__main__":mat=[[1,0,1],[1,1,0],[1,1,0]]print(countSquares(mat))
C#
usingSystem;publicclassGFG{publicstaticintCountSquares(int[][]mat){intn=mat.Length;intm=mat[0].Length;intres=0;// Consider every cell as top-left cornerfor(inti=0;i<n;i++){for(intj=0;j<m;j++){intmaxSize=Math.Min(n-i,m-j);// Try all possible square sizesfor(intsize=1;size<=maxSize;size++){boolvalid=true;// Check all cells of current squarefor(intr=i;r<i+size&&valid;r++){for(intc=j;c<j+size;c++){if(mat[r][c]==0){valid=false;break;}}}if(valid){res++;}else{break;}}}}returnres;}publicstaticvoidMain(){int[][]mat={newint[]{1,0,1},newint[]{1,1,0},newint[]{1,1,0}};Console.WriteLine(CountSquares(mat));}}
JavaScript
functioncountSquares(mat){letn=mat.length;letm=mat[0].length;letres=0;// Consider every cell as top-left cornerfor(leti=0;i<n;i++){for(letj=0;j<m;j++){letmaxSize=Math.min(n-i,m-j);// Try all possible square sizesfor(letsize=1;size<=maxSize;size++){letvalid=true;// Check all cells of current squarefor(letr=i;r<i+size&&valid;r++){for(letc=j;c<j+size;c++){if(mat[r][c]===0){valid=false;break;}}}if(valid){res++;}else{break;}}}}returnres;}// Driver Codeletmat=[[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>usingnamespacestd;intcountSquares(vector<vector<int>>&mat){intn=mat.size();intm=mat[0].size();vector<vector<int>>dp(n,vector<int>(m,0));intres=0;// Fill DP tablefor(inti=0;i<n;i++){for(intj=0;j<m;j++){// First row or first columnif(i==0||j==0){dp[i][j]=mat[i][j];}// Current cell is 1elseif(mat[i][j]==1){dp[i][j]=1+min({dp[i-1][j],// Topdp[i][j-1],// Leftdp[i-1][j-1]// Top-left});}// Add squares ending at current cellres+=dp[i][j];}}returnres;}intmain(){intn=3,m=3;vector<vector<int>>mat={{1,0,1},{1,1,0},{1,1,0}};cout<<countSquares(mat);return0;}
Java
importjava.util.Arrays;publicclassGFG{publicstaticintcountSquares(int[][]mat){intn=mat.length;intm=mat[0].length;int[][]dp=newint[n][m];intres=0;// Fill DP tablefor(inti=0;i<n;i++){for(intj=0;j<m;j++){// First row or first columnif(i==0||j==0){dp[i][j]=mat[i][j];}// Current cell is 1elseif(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 cellres+=dp[i][j];}}returnres;}publicstaticvoidmain(String[]args){intn=3,m=3;int[][]mat={{1,0,1},{1,1,0},{1,1,0}};System.out.println(countSquares(mat));}}
Python
defcountSquares(mat):n=len(mat)m=len(mat[0])dp=[[0]*mfor_inrange(n)]res=0# Fill DP tableforiinrange(n):forjinrange(m):# First row or first columnifi==0orj==0:dp[i][j]=mat[i][j]# Current cell is 1elifmat[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 cellres+=dp[i][j]returnresif__name__=="__main__":n,m=3,3mat=[[1,0,1],[1,1,0],[1,1,0]]print(countSquares(mat))
C#
usingSystem;publicclassGFG{staticintcountSquares(int[][]mat){intn=mat.Length;intm=mat[0].Length;int[][]dp=newint[n][];for(inti=0;i<n;i++){dp[i]=newint[m];}intres=0;// Fill DP tablefor(inti=0;i<n;i++){for(intj=0;j<m;j++){// First row or first columnif(i==0||j==0){dp[i][j]=mat[i][j];}// Current cell is 1elseif(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 cellres+=dp[i][j];}}returnres;}staticvoidMain(){int[][]mat={newint[]{1,0,1},newint[]{1,1,0},newint[]{1,1,0}};Console.WriteLine(countSquares(mat));}}
JavaScript
functioncountSquares(mat){letn=mat.length;letm=mat[0].length;letdp=Array.from({length:n},()=>Array(m).fill(0));letres=0;// Fill DP tablefor(leti=0;i<n;i++){for(letj=0;j<m;j++){// First row or first columnif(i===0||j===0){dp[i][j]=mat[i][j];}// Current cell is 1elseif(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 cellres+=dp[i][j];}}returnres;}// Driver Codeletn=3,m=3;letmat=[[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>usingnamespacestd;intcountSquares(vector<vector<int>>&mat){intres=0;intn=mat.size();intm=mat[0].size();// Traverse matrix row by rowfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Cell containing 0 cannot form a squareif(mat[i][j]==0){continue;}// Update square size using neighborsif(i>0&&j>0){mat[i][j]+=min({mat[i-1][j],// Topmat[i][j-1],// Leftmat[i-1][j-1]// Top-left});}// Add number of squares ending hereres+=mat[i][j];}}returnres;}intmain(){intn=3,m=3;vector<vector<int>>mat={{1,0,1},{1,1,0},{1,1,0}};cout<<countSquares(mat);return0;}
Java
importjava.util.Arrays;publicclassGFG{publicstaticintcountSquares(int[][]mat){intres=0;intn=mat.length;intm=mat[0].length;// Traverse matrix row by rowfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Cell containing 0 cannot form a squareif(mat[i][j]==0){continue;}// Update square size using neighborsif(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 hereres+=mat[i][j];}}returnres;}publicstaticvoidmain(String[]args){int[][]mat={{1,0,1},{1,1,0},{1,1,0}};System.out.println(countSquares(mat));}}
Python
defcountSquares(mat):res=0n=len(mat)m=len(mat[0])# Traverse matrix row by rowforiinrange(n):forjinrange(m):# Cell containing 0 cannot form a squareifmat[i][j]==0:continue# Update square size using neighborsifi>0andj>0:mat[i][j]+=min(mat[i-1][j],mat[i][j-1],mat[i-1][j-1])# Add number of squares ending hereres+=mat[i][j]returnresif__name__=="__main__":n,m=3,3mat=[[1,0,1],[1,1,0],[1,1,0]]print(countSquares(mat))
C#
usingSystem;publicclassGFG{staticintcountSquares(int[][]mat){intres=0;intn=mat.Length;intm=mat[0].Length;// Traverse matrix row by rowfor(inti=0;i<n;i++){for(intj=0;j<m;j++){// Cell containing 0 cannot form a squareif(mat[i][j]==0){continue;}// Update square size using neighborsif(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 hereres+=mat[i][j];}}returnres;}staticvoidMain(){int[][]mat=newint[][]{newint[]{1,0,1},newint[]{1,1,0},newint[]{1,1,0}};Console.WriteLine(countSquares(mat));}}
JavaScript
functioncountSquares(mat){letres=0;letn=mat.length;letm=mat[0].length;// Traverse matrix row by rowfor(leti=0;i<n;i++){for(letj=0;j<m;j++){// Cell containing 0 cannot form a squareif(mat[i][j]===0){continue;}// Update square size using neighborsif(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 hereres+=mat[i][j];}}returnres;}// Driver Codeletmat=[[1,0,1],[1,1,0],[1,1,0]];console.log(countSquares(mat));