原題目如下:
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
.
這個題目實際第一反應是對於任意一個點的值,去查找他邊上的三個點,但是這樣的效率就太低了.後來發現他的解實際上是可以複用的,這樣的話自然可以引入動態規劃,發現對應的遞推公式寫矩陣.
以當前點(x,y) 爲右下角的最大正方形的的邊長f(x,y) ;
f(x,y) =
min( f(x-1,y), f(x,y-1), f(x-1,y-1)) + 1 (matrix[x][y] = 1)
f(x,y)
= 0 (matrix[x][y] = 0);
那麼我們以這個遞推公式,寫一個f(x,y)的矩陣。返回這個矩陣的最大值的平方。就是這個結果了
代碼如下:
#include<string>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
int maxSquare(vector<vector<int> > &matrix) {
int n = matrix.size();
vector<vector<int>> MAX;
vector<int> tem;
//初始化結果數組
for(int i = 0; i != n; i++)
tem.push_back(0);
for(int i = 0; i != n; i++)
MAX.push_back(tem);
for(int i = 0; i != n; i++)
if(matrix[0][i] == 1)
MAX[0][i] = 1;
for(int i = 1; i != n; i++)
if(matrix[i][0] == 1)
MAX[i][0] = 1;
for(int i = 1; i != n; i++)
for(int j = 1; j != n; j++)
if(matrix[i][j] == 1)
{
int minest = min(min(MAX[i-1][j], MAX[i][j-1]), MAX[i-1][j-1]);
MAX[i][j] = minest + 1;
}
else
MAX[i][j] = 0;
int MAXmax = 0;
for(int i = 1; i != n; i++)
for(int j = 1; j != n; j++)
if(MAX[i][j] > MAXmax)
MAXmax = MAX[i][j];
return MAXmax * MAXmax;
}
};