题目链接:https://leetcode.com/problems/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 0Return 4.
思路:一道比较明显的动态规划题目。因为是要寻找一个正方形,所以就比较简单一些,借助一个辅助数组dp[][],dp[i][j]表示当前正方形的边长,并且其值由两种情况构成:
1. 如果matrix[i-1][j-1] = 1, 因为是正方形,则其值为min(dp[i-1][j-1],dp[i][j-1],dp[i-1][j])中的最小值加1,小正方形构成大正方形,状态转移方程即为:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1;
2. 如果matrix[i-1][j-1] = 0,则dp[i][j] = 0;
时间复杂度为O(m*n),空间复杂度为O(m*n)
代码如下:
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size() == 0) return 0; int max = 0, dp[matrix.size()+1][matrix[0].size()+1]; memset(dp, 0, sizeof(dp)); for(int i =1; i <= (int)matrix.size(); i++) { for(int j =1; j<= (int)matrix[0].size(); j++) { if(matrix[i-1][j-1] == '1') { dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1; if(dp[i][j] >= max) max = dp[i][j]; } else dp[i][j] = 0; } } return max*max; } };