【LeetCode 221】Maximal Square

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.

思路:

  DP,到达当前(非0)结点的最长边长square[i][j] = min(square[i-1][j-1], min(square[i-1][j], square[i][j-1])) + 1,即取左上方3个结点中值最小的一个加1。代码写的看起来好不舒服 - -!

 1 class Solution {

 2 public:

 3     int maximalSquare(vector<vector<char>>& matrix) {

 4         const int rows = matrix.size();

 5         if(rows == 0)

 6             return 0;

 7         

 8         vector<vector<char> >::iterator it = matrix.begin();

 9         const int columns = (*it).size();

10         

11         int square[rows][columns], ret = 0;

12         

13         for(int i = 0; i < rows; i++)

14             for(int j = 0; j < columns; j++)

15                 square[i][j] = 0;

16         

17         for(int i = 0; i < rows; i++){

18             if(matrix[i][0] == '1')

19             {

20                 square[i][0] = 1;

21                 ret = 1;

22             }

23         }

24     

25         for(int i = 0; i < columns; i++){

26             if(matrix[0][i] == '1')

27             {

28                 square[0][i] = 1;

29                 ret = 1;

30             }

31         }

32         

33         for(int i = 1; i < rows; i++)

34         {

35             for(int j = 1; j < columns; j++)

36             {

37                 square[i][j] = matrix[i][j] == '1' ? min(square[i-1][j], min(square[i][j-1], square[i-1][j-1])) + 1 : 0;

38                 

39                 if(square[i][j] > ret)

40                     ret = square[i][j];

41             }

42         }

43         return ret * ret;

44     }

45 };

 

你可能感兴趣的:(LeetCode)