码迷,mamicode.com
首页 > 其他好文 > 详细

Maximal Square

时间:2015-09-29 06:31:46      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

Runtime: 12ms.

 1 class Solution {
 2 public:
 3     int maximalSquare(vector<vector<char>>& matrix) {
 4         if(matrix.empty() || matrix[0].empty()) return 0;
 5         
 6         int row = matrix.size();
 7         int col = matrix[0].size();
 8         
 9         vector<vector<int> > dp(row, vector<int>(col, 0));
10         int result = 0;
11         for(int i = 0; i < row; i++)
12             if(matrix[i][0] == 1){
13                 dp[i][0] = 1;
14                 result = 1;
15             }
16             
17         for(int j = 0; j < col; j++)
18             if(matrix[0][j] == 1){
19                 dp[0][j] = 1;
20                 result = 1;
21             }
22             
23         for(int i = 1; i < row; i++){
24             for(int j = 1; j < col; j++){
25                 if(matrix[i][j] == 1){
26                     dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
27                     result = max(result, dp[i][j]);
28                 }
29             }
30         }
31         return result * result;
32     }
33 };class Solution {
34 public:
35     int maximalSquare(vector<vector<char>>& matrix) {
36         if(matrix.empty() || matrix[0].empty()) return 0;
37         
38         int row = matrix.size();
39         int col = matrix[0].size();
40         
41         vector<vector<int> > dp(row, vector<int>(col, 0));
42         int result = 0;
43         for(int i = 0; i < row; i++)
44             if(matrix[i][0] == 1){
45                 dp[i][0] = 1;
46                 result = 1;
47             }
48             
49         for(int j = 0; j < col; j++)
50             if(matrix[0][j] == 1){
51                 dp[0][j] = 1;
52                 result = 1;
53             }
54             
55         for(int i = 1; i < row; i++){
56             for(int j = 1; j < col; j++){
57                 if(matrix[i][j] == 1){
58                     dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1;
59                     result = max(result, dp[i][j]);
60                 }
61             }
62         }
63         return result * result;
64     }
65 };

 

Maximal Square

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4845396.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!