topic:
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 0Return 4.
Question link: https://leetcode.com/problems/maximal-square/ .
This question is a bit similar: Maximal Rectangle by LeetCode OJ . But the problem-solving method is completely different.
Ideas:
dynamic programming. Let f[i][j] represent the maximum variable length of the square containing the current point, there is a recursive relationship such as the following:
f[0][j] = matrix[0][j] f[i][0] = matrix[i][0] For i > 0 and j > 0: if matrix[i][j] = 0, f[i][j] = 0; if matrix[i][j] = 1, f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1.
Code 1:
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int row = matrix.size(); if(row == 0) return 0; int col = matrix[0].size(); vector<vector<int> > f(row , vector<int>(col , 0)); int maxsize = 0; // maximum side length for(int i = 0 ; i < row ; i++) { for(int j = 0 ; j < col ; j++) { if(i == 0 || j == 0) f[i][j] = matrix[i][j]-'0'; else { if(matrix[i][j] == '0') f[i][j] = 0; else f [i] [j] = min (min (f [i-1] [j], f [i] [j-1]), f [i-1] [j-1]) + 1; } maxsize = max(maxsize , f[i][j]); } } return maxsize * maxsize; } };
Code 2:
The optimization space is one-dimensional
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int row = matrix.size(); if(row == 0) return 0; int col = matrix[0].size(); vector<int> f(col , 0); int tmp1 = 0 , tmp2 = 0; int maxsize = 0; // maximum side length for(int i = 0 ; i < row ; i++) { for(int j = 0 ; j < col ; j++) { tmp1 = f[j]; //tmp1 saves the current f[j] below for the next inference f[i+1][j+1] of the upper left corner f[i-1][j-1] if(i == 0 || j == 0) f[j] = matrix[i][j]-'0'; else { if(matrix[i][j] == '0') f[j] = 0; else f[j] = min(min(f[j-1] , f[j]) , tmp2) + 1; //The tmp2 here is f[i-1][j-1] of code 1 } tmp2 = tmp1 ; //Assign tmp1 to tmp2 for the next for loop to find f[j+1] maxsize = max(maxsize , f[j]); } } return maxsize * maxsize; } };