Leetcode 221. Maximal Square (Medium) (cpp)

来源:互联网 发布:ipad加入网络密码错误 编辑:程序博客网 时间:2024/05/18 17:41

Leetcode 221. Maximal Square (Medium) (cpp)

Tag: Dynamic Programming

Difficulty: Medium


/*221. Maximal Square (Medium)Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.For example, given the following matrix:1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 4.*/class Solution {public:    int maximalSquare(vector<vector<char>>& matrix) {        if (matrix.empty()) {            return 0;        }        int row = matrix.size(), col = matrix[0].size();        vector<vector<int>> t(row, vector<int>(col, 0));        int cur = 0;        for (int i = 0; i < matrix.size(); i++) {            for (int j = 0; j < matrix[0].size(); j++) {                if (i == 0 || j == 0) {                    t[i][j] = matrix[i][j] - '0';                } else if (matrix[i][j] == '1'){                    t[i][j] = min(min(t[i - 1][j - 1], t[i][j - 1]), t[i - 1][j]) + 1;                }                cur = max(cur, t[i][j]);            }        }        return cur * cur;    }};


0 0
原创粉丝点击