tema
Dada una matriz binaria 2-D de tamaño que contiene solo 0
y , encuentre el rectángulo más grande que contenga solo y devuelva su área.1
rows x cols
1
Ejemplo 1:
Entrada: matriz = [["1","0","1","0","0"],["1","0","1","1","1"],[ "1","1","1","1","1"],["1","0","0","1","0"]] Salida: 6 Explicación : Rectángulo máximo Como se muestra en la FIG.
Ejemplo 2:
Entrada: matriz = [] Salida: 0
Ejemplo 3:
Entrada: matriz = [["0"]] Salida: 0
Ejemplo 4:
Entrada: matriz = [["1"]] Salida: 1
Ejemplo 5:
Entrada: matriz = [["0","0"]] Salida: 0
pista:
rows == matrix.length
cols == matrix[0].length
1 <= row, cols <= 200
matrix[i][j]
para'0'
o'1'
respuesta
código fuente
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[] heights = new int[n];
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
heights[j] += 1;
} else {
heights[j] = 0;
}
}
maxArea = Math.max(maxArea, largestRectangleArea(heights));
}
return maxArea;
}
public int largestRectangleArea(int[] heights) {
int[] left = new int[heights.length];
int[] right = new int[heights.length];
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < heights.length; i++) {
while (!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
stack.pop();
}
left[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(i);
}
stack.clear();
for (int i = heights.length - 1; i >= 0; i--) {
while(!stack.isEmpty() && heights[stack.peek()] >= heights[i]) {
stack.pop();
}
right[i] = stack.isEmpty() ? heights.length : stack.peek();
stack.push(i);
}
int maxArea = 0;
for (int i = 0; i < heights.length; i++) {
maxArea = Math.max(maxArea, (right[i] - left[i] - 1) * heights[i]);
}
return maxArea;
}
}
Resumir
Esta pregunta se responde basándose en "84. El rectángulo más grande en un gráfico de columnas". Desde la primera fila hasta la última fila, considere la fila actual hasta la parte superior como un gráfico de columnas, calcule la altura de cada columna y use la función. Se calcula el valor "84. El rectángulo más grande en el gráfico de columnas" y finalmente se obtiene el valor máximo por comparación.