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

Java中裁剪二维数组的有效方法,java,arrays,algorithm,multidimensional-array,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,

我有一个二维数组:

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”包围的零):

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

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

public static int[]trim(int[]mtx,int rmin,int rmax,int cmin,int cmax){
int[][]结果=新int[rmax rmin+1][];
对于(int r=rmin,i=0;rc)cmin=c;
如果(cmaxr)rmin=r;
如果(rmax
您尝试过什么吗?与查看周围的0或1不同,您的算法似乎是删除所有项目总和为0.1的行和列,2. @或者只有当他们排在第一或最后的时候。第一列和最后两列应该删除,以便。。。也许这是一个
第一个和最后一个N
把戏,或者可能是总和:)
        {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));
}