[JAVA]  DP 7ms, with explanation, O(m*n) time, 100% space
if matrix[i][j] == 0, skip\n2.  use bottom right to count the square, if a 2 * 2 grid like\n" A B "\n" C X "\nevery character means the nums of the square that 
1. if matrix[i][j] == 0, skip\n2.  use bottom right to count the square, if a 2 * 2 grid like\n" A B "\n" C X "\nevery character means the nums of the square that position can represent. For example A = 2 represents 2 squares in the "A" position, one is itself and the other is a 2 * 2 square , a 2 * 2 square means A is in the position like \n" 1 1 "\n" 1 A "\nso X should be Math.min(A+1, B+1, C+1) which ensures X is in the postion like \n" 1 ... 1 "     //k * k, k =  Math.min(A+1, B+1, C+1) \n" 1 .... . "\n" 1 ... X "\nfor example\n![image](https://assets.leetcode.com/users/zmajia/image_1576728999.png)\nin the yellow grid, we know (D4=3) (E4=2) (D5=2) and then how to calculate the (E5).\nD4 = 3 means the largest sqaure it can represent is the black one(3* 3) === we can find 3 sqaures which its bottom right is D4 (1* 1, 2* 2, 3* 3 squares).\nThen the same as E4(red square) and D5(green one). When it comse to E5,  (E5) = Math.min(D4+1, E4+1, D5+1) means the largest square E5 can represent which is (C3 ~ E5)\n\n3. because we are using the bottom right to count the square, the "A B C" will always be calculated before "X". So just go through the grid then and add all nums in the grid\n```\nclass Solution {\n    public int countSquares(int[][] matrix) {\n        if(matrix == null)\n             return 0;\n        int ret = 0;\n        for(int i = 0; i < matrix.length; i++) {\n            for(int j = 0; j < matrix[0].length; j++) {\n                if(matrix[i][j] == 0)\n                    continue;\n                if(i >= 1 && j >= 1){\n                    matrix[i][j] = Math.min(\n                     Math.min(matrix[i-1][j-1] + 1,matrix[i-1][j] + 1),\n                        matrix[i][j-1] + 1);\n                } \n                ret += matrix[i][j];\n               // System.out.println(i + " " + j + " " + matrix[i][j]);\n            }\n        }\n        return ret;\n    }\n}\n```
['Dynamic Programming', 'Java']