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 1 1 1 11 0 0 1 0
Return 4.
1 Public classSolution {2 Public intMaximalsquare (Char[] matrix) {3 introws =matrix.length;4 if(rows = = 0)return0;5 intcols = matrix[0].length;6 if(cols = = 0)return0;7node[][] STA =NewNode[rows][cols];8 for(inti=0; i<rows; i++){9 for(intj=0; j<cols; J + +){TenSTA[I][J] =NewNode (); One } A } - - intres = 0; the - if(matrix[0][0] = = ' 1 '){ -Sta[0][0].left = 1; -Sta[0][0].up = 1; +Sta[0][0].maxsize = 1; -res = 1; + } A //ask for the first line at for(intI=1; i<cols; i++){ - if(Matrix[0][i] = = ' 1 '){ -Sta[0][i].left = sta[0][i-1].left+1; -Sta[0][i].maxsize = 1; -res = 1; - } in } - //find the first column to for(intj=1;j<rows;j++){ + if(matrix[j][0] = = ' 1 '){ -Sta[j][0].up = sta[j-1][0].up + 1; theSta[j][0].maxsize = 1; *res = 1; $ }Panax Notoginseng } - //Dynamic Seeking other the for(intI=1; i<rows; i++){ + for(intJ=1; j<cols; J + +){ A if(Matrix[i][j] = = ' 1 '){ theSta[i][j].left = sta[i-1][j].left + 1; +Sta[i][j].up = sta[i][j-1].up + 1; -Sta[i][j].maxsize = 1; $ if(Matrix[i-1][j-1] = = ' 1 '){ $Sta[i][j].maxsize =math.min (Sta[i][j].left, sta[i][j].up); -Sta[i][j].maxsize = Math.min (Sta[i][j].maxsize, sta[i-1][j-1].maxsize+1); - } the - }Wuyires =Math.max (sta[i][j].maxsize, res); the } - } Wu - returnRes*Res; About $ } - - classnode{ - intLeft ; A intUp ; + intmaxSize; the } - $}
Dynamic Programming Example: Maximal Square