You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java二维数组边界补0邻域中位数计算实现求助

二维数组3x3邻域中位数计算(边界补0)实现

问题核心规则

  • 计算二维数组每个元素的3x3邻域中位数时,边界/角落位置缺失的邻接元素统一按0处理,等效于在原数组外围包裹一圈值为0的虚拟元素
  • 示例原数组:
array2D = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

原矩阵形态:

1 2 3
4 5 6
7 8 9

补0后的等效计算矩阵:

0 0 0 0 0
0 1 2 3 0
0 4 5 6 0
0 7 8 9 0
0 0 0 0 0

以左上角元素1为例,参与中位数计算的邻域值集合为0, 0, 0, 0, 1, 2, 0, 4, 5。

现有代码问题

原有循环逻辑仅能遍历原数组范围内存在的元素,没有处理邻域坐标越界的情况,无法自动补入缺失的0值,未完成代码片段如下:

public static double[][] media(double[][] X)
{
    int numRows = X.length;
    int numCols = X[0].length;
    double[][] arrayMedian = new double[numRows][numCols];
    for(int row = 0; row < numRows; row++) {
        for(int col = 0; col < numCols; col++) {
            for (int i = Math.max(0, row -1); i < Math.min(numRows, row + 2); i++) {
                for (int j = Math.max(0, col -1); j < Math.min(numCols, col + 2); j++) {
                    //do stuff

测试用数组定义在main方法中:

double[][] X = {{1,2,3}, {4,5,6}, {7,8,9}};

实现方案

不需要额外构造补0后的扩展矩阵,直接遍历每个元素对应的9个3x3邻域偏移位置,越界则补0,不越界则取原数组对应值,收集完9个邻域值后排序取中位数即可。
完整可运行代码:

import java.util.Arrays;

public class MedianCalc {
    public static double[][] media(double[][] X) {
        int numRows = X.length;
        if (numRows == 0) return new double[0][0];
        int numCols = X[0].length;
        double[][] arrayMedian = new double[numRows][numCols];
        
        // 预定义3x3邻域的9组坐标偏移量
        int[] dRow = {-1, -1, -1, 0, 0, 0, 1, 1, 1};
        int[] dCol = {-1, 0, 1, -1, 0, 1, -1, 0, 1};

        for (int row = 0; row < numRows; row++) {
            for (int col = 0; col < numCols; col++) {
                double[] neighbors = new double[9];
                for (int k = 0; k < 9; k++) {
                    int curR = row + dRow[k];
                    int curC = col + dCol[k];
                    // 坐标越界则补0,否则取原数组值
                    neighbors[k] = (curR < 0 || curR >= numRows || curC < 0 || curC >= numCols) 
                        ? 0 
                        : X[curR][curC];
                }
                // 9个元素排序后,索引4的位置就是中位数
                Arrays.sort(neighbors);
                arrayMedian[row][col] = neighbors[4];
            }
        }
        return arrayMedian;
    }

    public static void main(String[] args) {
        double[][] X = {{1,2,3}, {4,5,6}, {7,8,9}};
        double[][] result = media(X);
        // 打印结果验证
        for (double[] row : result) {
            for (double val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

逻辑说明

  • 提前写死3x3邻域的偏移量,避免多层循环做范围裁剪时遗漏补0逻辑
  • 每个邻域位置单独做越界判断,完全匹配“外围补一圈0”的计算规则,不需要额外占用内存存储扩展矩阵
  • 邻域固定为9个元素,排序后直接取第5个元素(索引4)即可得到中位数,无需额外处理奇偶长度判断
  • 针对示例测试用例,左上角元素的邻域值排序后为[0,0,0,0,0,1,2,4,5],计算得到中位数为0,完全符合需求规则。

内容的提问来源于stack exchange,提问作者Max Ringnalda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 12:42:17