[leetcode] Maximal Square

Maximal Square

  • 問題描述:在一個給定的矩陣中,找到一個最大的方陣。矩陣中的元素都是0或者1.方陣內的元素要求都是1.
  • 動態規劃:dp[i][j]代表以ij結束的點所能構成的最大方陣的邊長。
    • 轉移方程dp[i][j] = min{dp[i-1][j-1], dp[i-1][j], dp[i][j-1]} + 1. 注意這裏min相當於計算交集。
//
// Created by 樑棟 on 2019-05-15.
//
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size();
        if(m == 0)
            return 0;
        int n = matrix[0].size();
        int dp[m+1][n+1];
        memset(dp, 0, sizeof(dp));
        int max = 0;
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;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;
                    max = max > dp[i][j] ? max: dp[i][j];
                }
            }
        }
        return max * max;
    }
    int maximalSquareV2(vector<vector<char>>& matrix) {
        int m = matrix.size();
        if(m == 0)
            return 0;
        int n = matrix[0].size();
        vector<int> pre(n+1, 0);
        vector<int> cur(n+1, 0);
        int max = 0;
        for(int i=1;i<=m;i++){
            for(int j=1;j<=n;j++){
                if(matrix[i-1][j-1] == '1'){
                    cur[j] = min(cur[j-1], min(pre[j], pre[j-1])) + 1;
                    max = max > cur[j] ? max: cur[j];
                }else{
                    cur[j] = 0;
                }
            }
            cout<<max<<endl;
            fill(pre.begin(), pre.end(), 0);
            swap(pre, cur);
        }
        return max * max;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章