leetcode之Maximal Square
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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[i][j]表示以matrix[i][j]结尾的最大正方形,则初始化:dp[i][j]=matrix[i][j],0<=i<=m,0<=j<=n(m,n为matrix的行数和列数)
状态转移方程:
dp[i][j] = MIN(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1,if matrix[i-1][j-1] == '1' and matrix[i][j] == '1' and matrix[i-1][j] == '1' and matrix[i][j-1] == '1'
代码:
class Solution { #define MIN(a,b,c) (a)<=(b)?((a)<=(c)?(a):(c)):((b)<=(c)?(b):(c)) public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.empty()) { return 0; } int m = matrix.size(); int n = matrix[0].size(); int dp[m+1][n+1]; int max = 0; for(int i = 0;i < m;i ++) { for(int j = 0;j < n;j++) { if(matrix[i][j] == '1') dp[i][j] = 1; else dp[i][j] = 0; if(max < dp[i][j]) max = dp[i][j]; } } for(int i = 1;i < m;i ++) { for(int j = 1;j < n;j++) { if(matrix[i-1][j-1] == '1' && matrix[i][j] == '1' && matrix[i-1][j] == '1' && matrix[i][j-1] == '1') { int n = MIN(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]); dp[i][j] = n + 1; } else { } if(max < dp[i][j]) max = dp[i][j]; } } return max * max; } };