在Java中修剪2D数组的有效方法

时间:2018-06-19 12:15:10

标签: java arrays algorithm multidimensional-array

我有以下二维数组:

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}
};

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

        {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}

我正在寻找一种有效的方法。

1 个答案:

答案 0 :(得分:3)

可能的解决方案(如果是最有效的方法,则不知道):

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));
}