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.

二. 题目分析

题目大意是,给定一个二维矩阵(只包含字符'0''1'),从中找出最大的全1正方形矩阵并返回其面积。

比如以下矩阵:

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

最大全1区域是2×2,返回4

该题目可使用动态规划来解决,只需列出以下状态转换方程:

dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1

其中,dp[i][j]表示以矩阵当前下标的元素为Square的左下角,所能组成的Square尺寸。另外,在遍历过程中,使用一个变量maxSizedp[i][j]比较,以获得最大的尺寸。

三. 示例代码

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        int m = matrix.size();
        if (m == 0) return 0;
        int n = matrix[0].size(), maxSize = 0;
        vector<vector<int>> record(m, vector<int>(n, 0));
        // 初始化record矩阵
        for (int i = 0; i < m; ++i) {
            if (matrix[i][0] == '1') {
                while (i < m) record[i++][0] = 1;
                maxSize = 1;
            }
        }
        for (int j = 0; j < n; ++j) {
            if (matrix[0][j] == '1') {
                while(j < n) record[0][j++] = 1;
                maxSize = 1;
            }
        }
        // DP
        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++j) {
                if (matrix[i - 1][j - 1] == '1' && matrix[i - 1][j] == '1' && matrix[i][j - 1] == '1' && matrix[i][j] == '1') {
                    record[i][j] = min(record[i - 1][j - 1], min(record[i - 1][j], record[i][j - 1])) + 1;
                    if (record[i][j] > maxSize) maxSize = record[i][j];
                }
                else if (matrix[i][j] == '1') record[i][j] = 1;
                else record[i][j] = 0;
            }
        }
        return maxSize * maxSize;
    }
};

四. 小结

该版本的代码一口气写出来,但总感觉不够简洁,还需继续改进。

你可能感兴趣的:(LeetCode,C++,dp,动态规划,Matrix)