分析:dp[i][j]表示右下角坐标为(i,j)的最大正方形边长,累加即可
class Solution { public int countSquares(int[][] matrix) { if(matrix.length == 0 || matrix[0].length == 0) return 0; int m = matrix.length, n = matrix[0].length; int[][] dp = new int[m][n]; // dp[i][j]表示以(i,j)为右下角的最大正方形边长 int res = 0; for(int i = 0; i < m; i++) { dp[i][0] = matrix[i][0]; res += dp[i][0]; } for(int i = 1; i < n; i++) { dp[0][i] = matrix[0][i]; res += dp[0][i]; } for(int i = 1; i < m; i++) { for(int j = 1; j < n; j++) { if(matrix[i][j] == 1) dp[i][j] = Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1])) + 1; res += dp[i][j]; } } return res; } }