// !!!!!!!!!!!!TLE!!!!!!!!!!!!!!!classSolution{privateintROWS;privateintCOLS;// Map cell and its maxlength of squareprivateMap<int[],Integer> map;publicintmaximalSquare(char[][] matrix){ROWS= matrix.length;COLS= matrix[0].length;
map =newHashMap();// Start findinghelper(0,0, matrix);int maxArea =0;// Obtain the max areafor(int area : map.values()){
maxArea =Math.max(maxArea, area);}return maxArea * maxArea;}// top down finding helperprivateinthelper(int r,int c,char[][] matrix){// Out of boundif(r >=ROWS|| c >=COLS)return0;int[] curCell =newint[]{r, c};if(!map.containsKey(curCell)){int down =helper(r +1, c, matrix);int right =helper(r, c +1, matrix);int diag =helper(r +1, c +1, matrix);// Store current cell
map.put(curCell,0);// Could be a bigger squareif(matrix[r][c]=='1'){
map.put(
curCell,1+Math.min(Math.min(down, right), diag));}}return map.get(curCell);}}
DP解法
classSolution{publicintmaximalSquare(char[][] matrix){finalintROWS= matrix.length;finalintCOLS= matrix[0].length;int[][] dp =newint[ROWS+1][COLS+1];// Length of the squareint maxLength =0;// From bottom to the topfor(int row =ROWS-1; row >=0;--row){for(int col =COLS-1; col >=0;--col){// Can be a bigger squareif(matrix[row][col]=='1'){// Update current cell's value
dp[row][col]=1+Math.min(Math.min(dp[row][col +1], dp[row +1][col]),
dp[row +1][col +1]);// Update the length of the largest square
maxLength =Math.max(maxLength, dp[row][col]);}}}return maxLength * maxLength;}}