leetcode Maximal Square

系统管理员 2022-08-01 06:12 266阅读 0赞

题目

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.
题目来源:https://leetcode.com/problems/maximal-square/

分析

动态规划。关注正方形右下角,dp[i][j]存储以当前顶点为正方形右下角的正方形的边长。遍历的过程中如果matrix[i][j] == ‘1’,则dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1;如果matrix[i][j] == ‘0’,那dp[i][j]肯定是0了。

代码

  1. class Solution {
  2. public:
  3. int maximalSquare(vector<vector<char>>& matrix) {
  4. int m = matrix.size();
  5. if(m == 0)
  6. return 0;
  7. int n = matrix[0].size();
  8. vector<vector<int> > dp(m, vector<int>(n, 0));
  9. int ans = 0;
  10. for(int i = 0; i < m; i++)
  11. if(matrix[i][0] == '1'){
  12. dp[i][0] = 1;
  13. ans = 1;
  14. }
  15. for(int j = 0; j < n; j++)
  16. if(matrix[0][j] == '1'){
  17. dp[0][j] = 1;
  18. ans = 1;
  19. }
  20. for(int i = 1; i < m; i++)
  21. for(int j = 1; j < n; j++)
  22. if(matrix[i][j] == '1'){
  23. dp[i][j] = min(dp[i-1][j], min(dp[i-1][j-1], dp[i][j-1])) + 1;
  24. ans = max(ans, dp[i][j]);
  25. }
  26. else
  27. dp[i][j] = 0;
  28. return ans*ans;
  29. }
  30. };

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读