221. Maximal Square

来源:互联网 发布:淘宝网页版回收站 编辑:程序博客网 时间:2024/05/17 23:37


My Submissions
Total Accepted: 33186 Total Submissions: 136598 Difficulty: Medium

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 01 0 1 1 11 1 1 1 11 0 0 1 0
Return 4.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question



class Solution {public:    int maximalSquare(vector<vector<char>>& matrix) {       int i=0,j=0,ii,jj,k=0,max=0,c;for(i=0;i<matrix.size();i++)for(j=0;j<matrix[0].size();j++){if(matrix[i][j]=='0') continue;        ii=i;jj=j;c=0;   while(++c)   {             ii++;jj++; if(ii>=matrix.size()||jj>=matrix[0].size())    break;          k=c;  if(matrix[ii][jj]=='0') break;    while(k--) //横向纵向同步检测   {if(i+k>=matrix.size()||j+k>=matrix[0].size())break;  if( matrix[i+k][jj]=='0'|| matrix[ii][j+k]=='0'   )  {k=-100;break; }    }      if(k== -100)break;//表示本次检测未通过,结束循环      }          if(c>max) max=c;     }  return max*max;}};




0 0
原创粉丝点击