3 4
2 0 7 9
0 6 9 7
8 4 6 4
8
样例输出
6
package algorithm.lanQiao.暴力剪枝;
import java.io.*;
public class 最大子矩阵
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException
{
String[] ss = in.readLine().split(" ");
int n = Integer.parseInt(ss[0]);
int m = Integer.parseInt(ss[1]);
int[][] g = new int[n][m];
for (int i = 0; i < n; i++)
{
ss = in.readLine().split(" ");
for (int j = 0; j < m; j++)
g[i][j] = Integer.parseInt(ss[j]);
}
int limit = Integer.parseInt(in.readLine());
int res = 1;
for (int i = 0; i < n; i++)// 枚举 行首
for (int j = 0; j < m; j++)// 枚举 列首
for (int x = i; x < n; x++)// 枚举 行尾
{
// 投机取巧小剪枝(过最后的 10% 案例)
int kx = Integer.MAX_VALUE;
int ky = Integer.MAX_VALUE;
for (int y = j; y < m; y++)// 枚举 列尾
{
if (x >= kx && y >= ky)
continue;
if (check(g, i, j, x, y) <= limit)// 判断最大差
{
res = Math.max(res, (x - i + 1) * (y - j + 1));
} else
{
kx = x;
ky = y;
break;
}
}
}
System.out.println(res);
}
private static int check(int[][] g, int xs, int ys, int xe, int ye)
{
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = xs; i <= xe; i++)
for (int j = ys; j <= ye; j++)
{
max = Math.max(max, g[i][j]);
min = Math.min(min, g[i][j]);
}
return max - min;
}
}