原题链接在这里:https://leetcode.com/problems/maximal-square/
题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0
Return 4.
题解:
DP, 状态: 以当前点为右下角的最大都包含1的square边长.
转移方程 如果当前点为1, dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])+1.
初始化dp[m+1][n+1], 多一行一列方便处理边界.
res 一直取maintain dp的最大值.
优化dp成一行, 因为只需要左, 上, 和左斜上三个值. prev 来保存左斜上.
Time Complexity: O(m*n). m = matrix.length, n = matrix[0].length.
Space: O(n).
AC Java:
1 public class Solution { 2 public int maximalSquare(char[][] matrix) { 3 if(matrix == null || matrix.length == 0 || matrix[0].length == 0){ 4 return 0; 5 } 6 7 int res = 0; 8 int m = matrix.length; 9 int n = matrix[0].length; 10 int [] dp = new int[n+1]; 11 int prev = 0; 12 13 for(int i = 1; i<=m; i++){ 14 for(int j = 1; j<=n; j++){ 15 int temp = dp[j]; 16 if(matrix[i-1][j-1] == '1'){ 17 dp[j] = Math.min(Math.min(dp[j], dp[j-1]), prev) + 1; 18 }else{ 19 dp[j] = 0; 20 } 21 prev = temp; 22 res = Math.max(res, dp[j]); 23 } 24 } 25 return res*res; 26 } 27 }