[中等]最大正方形

题目来源:http://www.lintcode.com/zh-cn/problem/maximal-square/

利用动态规划得到公式rst[i+1][j+1] = min(min(rst[i][j+1],rst[i+1][j]),rst[i][j])+1;

比如输入:

1 0 1 0 0

1 0 1 1 1

1 1 1 1 1

1 0 0 1 0

则输出:

1 0 1 0 0

1 0 1 1 1

1 1 1 2 2

1 0 0 1 0

C++版 VS2012测试通过:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 class Solution {
 6 public:
 7     /**
 8      * @param matrix: a matrix of 0 and 1
 9      * @return: an integer
10      */
11     int maxSquare(vector<vector<int> > &matrix) {
12         int m=matrix.size();
13         int n=matrix[0].size();
14         int max=0;
15         vector<vector<int> > rst(m+1,vector<int>(n+1,0));
16         for(int i=0;i<m;i++)
17             for(int j=0;j<n;j++)
18             {
19                 if(matrix[i][j])
20                 {
21                     rst[i+1][j+1] = min(min(rst[i][j+1],rst[i+1][j]),rst[i][j])+1;
22                     if(rst[i+1][j+1]>max)
23                         max=rst[i+1][j+1];
24                 }
25             }        
26         return max*max;       
27     }
28 };
29 
30 int main()
31 {
32     int m,n; // m行,n列     
33     cin>>m>>n;    
34     vector<vector<int> > input(m,vector<int>(n,0));    
35     for(int i=0;i<m;i++)
36         for(int j=0;j<n;j++)
37             cin >> input[i][j];
38     Solution s;
39     int rlt=s.maxSquare(input);
40     cout<<rlt;
41 }

输出

posted @ 2016-07-15 16:09  Pearl_zju  阅读(198)  评论(0编辑  收藏  举报