Maximal Square

Description:

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.

Code:

 1  int maximalSquare(vector<vector<char>>& matrix) {
 2         int m = matrix.size();
 3         if (m==0)
 4             return 0;
 5         int n = matrix[0].size();
 6         int maxSize = 0;
 7         vector<vector<int>>d (m, vector<int>(n,0));
 8         for (int i = 0; i < n; ++i)
 9         {
10             if (matrix[0][i]=='1')
11             {
12                 d[0][i] = 1;
13                 maxSize = 1;
14             }
15         }
16         for (int j = 0; j < m; ++j)
17         {
18             if (matrix[j][0]=='1')
19             {
20                 d[j][0] = 1;
21                 maxSize = 1;
22             }
23         }
24         for (int i = 1; i < m; ++i)
25         {
26             for (int j = 1; j < n; ++j)
27             {
28                 if (matrix[i][j]=='1')
29                 {
30                     int temp = min(d[i-1][j],d[i][j-1]);
31                     d[i][j] = min(temp,d[i-1][j-1])+1;
32                     if (d[i][j] > maxSize)
33                         maxSize = d[i][j];
34                 }
35             }
36         }
37         return maxSize*maxSize;
38     }

 

posted @ 2015-06-19 10:25  Rosanne  阅读(141)  评论(0编辑  收藏  举报