Leetcode--221-Maximal Square
221. Maximal Square
Description Submission Solutions
- Total Accepted: 52663
- Total Submissions: 191381
- Difficulty: Medium
- Contributors: Admin
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 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0Return 4.
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
Show Similar Problems
Have you met this question in a real interview?
题解: dp最简单的形式
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { if(matrix.size()==0 || matrix[0].size()==0){ return 0; } int row = matrix.size(), column = matrix[0].size(); vector<vector<int> > dp(row+1, vector<int>(column+1, 0)); int ans = 0; for(int i=0; i<row; ++i){ for(int j=0; j<column; ++j){ if( matrix[i][j] == '1' ){ dp[i+1][j+1] = min(dp[i][j], min(dp[i+1][j], dp[i][j+1])) + 1; if(ans < dp[i+1][j+1]){ ans = dp[i+1][j+1]; } } } } return (ans*ans); } };