Java O(N*M) Solution Using Dp
\nclass Solution {\n    public int countSquares(int[][] ar) {\n        int n = ar.length, m = ar[0].length;\n\t\tint dp[][] = new int[n][m];\n\t\tfor (int i = 0
```\nclass Solution {\n    public int countSquares(int[][] ar) {\n        int n = ar.length, m = ar[0].length;\n\t\tint dp[][] = new int[n][m];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tdp[i][j] = ar[i][j];\n\t\t\t}\n\t\t}\n\t\tfor (int i = 1; i < n; i++) {\n\t\t\tfor (int j = 1; j < m; j++) {\n\t\t\t\tint x = dp[i - 1][j - 1];\n\t\t\t\tint y = dp[i][j - 1];\n\t\t\t\tint z = dp[i - 1][j];\n\t\t\t\tint max = Integer.max(x, Integer.max(y, z));\n\t\t\t\tint min = Integer.min(x, Integer.min(y, z));\n\t\t\t\tif (dp[i][j] != 0 && x != 0 && y != 0 && z != 0) {\n\t\t\t\t\tdp[i][j] = min + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tint total = 0;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfor (int j = 0; j < m; j++) {\n\t\t\t\tint x = dp[i][j];\n\t\t\t\ttotal += x;\n\t\t\t}\n\t\t}\n        return total;\n    }\n}\n```
[]