在 Java 中修剪二维数组的有效方法

扬·斯洛明斯基

我有以下二维数组:

int[][] array = new int[][]{
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
        {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
        {0, 0, 1, 1, 0, 1, 1, 0, 0, 0},
        {0, 0, 1, 1, 0, 1, 0, 0, 0, 0},
        {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
        {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
        {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}
};

并且我想修剪所有周围的零,所以我的输出将是这样的(去除外面的“零”并保留被“一”包围的零):

        {0, 1, 1, 1, 0},
        {0, 1, 1, 1, 1},
        {1, 1, 0, 1, 1},
        {1, 1, 0, 1, 0},
        {0, 1, 1, 1, 1},
        {0, 1, 1, 1, 1},
        {0, 0, 0, 1, 0}

我正在寻找一种有效的方法来做到这一点。

奥内罗斯

可能的解决方案(不知道它是否是最有效的方法):

public static int[][] trim(int[][] mtx, int rmin, int rmax, int cmin, int cmax) {
   int[][] result = new int[rmax-rmin+1][];
   for (int r = rmin, i = 0; r <= rmax; r++, i++) {
      result[i] = Arrays.copyOfRange(mtx[r], cmin, cmax+1);
   }
   return result;
}

public static int[][] trim(int[][] mtx, int trimmed) {
   int cmin = mtx[0].length;
   int rmin = mtx.length;
   int cmax = -1;
   int rmax = -1;

   for (int r = 0; r < mtx.length; r++)
      for (int c = 0; c < mtx[0].length; c++)
         if (mtx[r][c] != trimmed) {
            if (cmin > c) cmin = c;
            if (cmax < c) cmax = c;
            if (rmin > r) rmin = r;
            if (rmax < r) rmax = r;
         }

   return trim(mtx, rmin, rmax, cmin, cmax);
}

public static void main (String[] args) {
   int[][] array = new int[][]{
      {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
      {0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
      {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
      {0, 0, 1, 1, 0, 1, 1, 0, 0, 0},
      {0, 0, 1, 1, 0, 1, 0, 0, 0, 0},
      {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
      {0, 0, 0, 1, 1, 1, 1, 0, 0, 0},
      {0, 0, 0, 0, 0, 1, 0, 0, 0, 0}
   };
   int[][] trim = trim(array, 0);
   System.out.println(Arrays.deepToString(trim));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章