Java O(mn) solution with O(1) space.
\nclass Solution {\n    public int countSquares(int[][] matrix) {\n        int n = matrix.length, m = matrix[0].length,count = 0;    \n        for(int i = 0;i<n
```\nclass Solution {\n    public int countSquares(int[][] matrix) {\n        int n = matrix.length, m = matrix[0].length,count = 0;    \n        for(int i = 0;i<n;i++) {\n            for(int j = 0;j<m;j++) {\n                if(matrix[i][j] == 1 && j > 0 && i > 0) {\n                         matrix[i][j] = Math.min(matrix[i-1][j-1],\n                                                 Math.min(matrix[i-1][j],matrix[i][j-1])) + 1;\n                     }\n                     count += matrix[i][j];\n                }\n        }\n        return count;\n    }\n}\n```
[]