假设我有一个矩阵
int[][] matrix = {
// 0 1 2
{0,0, 0,0, 0,0}, // 0
{0,1, 0,0, 0,0},
{1,1, 0,0, 0,0}, // 1
{0,0, 0,0, 0,1}
};
int newCellSize = 2;
我希望通过保持单元格的最大值来减少它。例如,
matrix
=>
int[][] reducedMatrix = {
{1, 0, 0},
{1, 0, 1}
};
我该怎么做?如何遍历matrix
元素并将它们映射到reducedMatrix
单元格?
这是我的尝试:
private static int[][] reduceMatrix(int[][] matrix, int cellSize) {
int a = (int)ceil((double)matrix.length/cellSize);
int b = (int)ceil((double)matrix[0].length/cellSize);
int[][] reduced = new int[a][b];
for(int i=0; i < matrix.length; i++){
for(int j=0; j < matrix[i].length; j++){
int n= i / cellSize;
int m= j / cellSize;
int elem = matrix[i][j];
if(elem > 0){
reduced[n > 0 ? n : 0][m > 0 ? m : 0]=elem;
}
}
}
return reduced;
}
答案 0 :(得分:0)
这段代码应该可以解决问题:
int[][] reduceMatrix(int[][] matrix, int cellSize, int rows, int cols) {
int [][] reducedMatrix = new int[rows/cellSize][cols/cellSize];
for (int i=0; i<rows; i+=cellSize) {
for (int j=0; j<cols; j+=cellSize) {
int max=-INF;
for (k=i;k<cellSize;k++)
for (l=j;l<cellSize;l++)
if (matrix[k][l]>max)
max=matrix[k][l];
reducedMatrix[i/cellSize][j/cellSize] = max;
}
}
return reducedMatrix;
}