c++ || 90% fast, O(1) space,dynamic programming
Idea is pretty simple , traverse in matrix \n\tif current element is 1 then crrent element=1+ min (prev diagonal element, prev horizontal, prev vertical element
1. Idea is pretty simple , traverse in matrix \n\t**if current element is 1 then crrent element=1+ min (prev diagonal element, prev horizontal, prev vertical element)**\n\ti.e m[i][j]=1+min( m[i-1][j-1],m[i][j-1],m[i-1][j] )\n\twhy this ? because theses 4 elemnts makes sqare of size 2, iteratively doing for all elements generate all squares of size 2,3 ,4... that is possible\n2- for better understanding once draw matrix and apply above logic\n3- result is summation of all values of matrices after above logic\n\n4-this approach required O(1) space \n5-same approach can also be used for getting maximum size square\n\t\t\tmax value of whole matrix is tha answer of this problem\n6-please upvote if you find this helpful.\t\t\t\n\t\t\t\n\t\n```\nclass Solution {\npublic:\n    int countSquares(vector<vector<int>>& matrix) {\n        int res=0;\n        for(int i=1;i<matrix.size();i++){\n            for(int j=1;j<matrix[0].size();j++){\n                if(matrix[i][j]>0){\n                    matrix[i][j]=1+min({matrix[i-1][j-1],matrix[i-1][j],matrix[i][j-1]});\n                }\n                res+=matrix[i][j];\n            }\n        }\n        for(int i=0;i<matrix.size();i++)res+=matrix[i][0]; // 1 lenth square matrix first column\n        for(int i=0;i<matrix[0].size();i++)res+=matrix[0][i]; // 1 lenth square matrix first row \n        if(matrix[0][0]==1)res-=1; // [0][0] will be counted twice;\n        return res;\n    }\n};\n\n```
['Dynamic Programming', 'C']