动态转移方程为:matrix[i][j] = Math.min(Math.min(matrix[i-1][j-1], matrix[i][j-1]), matrix[i-1][j]) + 1;
JAVA
class Solution { public int countSquares(int[][] matrix) { int r = matrix.length; int c = matrix[0].length; if(r == 0 || c == 0) return 0; int res = 0; for(int i = 1; i < r; i++){ for(int j = 1; j < c; j++){ if(matrix[i][j] != 0) matrix[i][j] = Math.min(Math.min(matrix[i-1][j-1], matrix[i][j-1]), matrix[i-1][j]) + 1; } //关键点在于Math.min的使用 } for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ res += matrix[i][j]; } } return res; } }
Python3
class Solution: def countSquares(self, matrix: List[List[int]]) -> int: r = len(matrix) c = len(matrix[0]); res = 0 for i in range(r): for j in range(c): if matrix[i][j] > 0 and i > 0 and j > 0: matrix[i][j] = min(matrix[i-1][j-1], matrix[i-1][j], matrix[i][j-1])+1 res += matrix[i][j] return res