数组—如何在java中切分或复制矩阵的中心部分

t0ybt7op  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(269)

void cropCenterPart (int a[][],int rows,int cols) → 此函数应提取中心部分并从arr打印,中心部分包括除边界以外的所有内容(边界包括第一行、第一列、最后一行和最后一列)。
注意:main函数中创建了一个矩阵。我必须通过传递签名来使用这个函数
原始矩阵
1 2 3 4
6 7 8 9
1 1 1 1
6 7 8 9
带中心的矩阵。
7 8
1 1
我还使用了arrays.copyofrange(array,start,end),但它给我空值或地址,不会打印任何内容。
附上一些密码

public void cropCenterPart(int a[][],int rows,int cols){

        for (int i = 0; i < rows; i++) { 
        for (int j = 0; j < cols; j++) { 
            if (i == 0) 
                System.out.print(a[i][j] + " "); 
            else if (i == rows - 1) 
                System.out.print(a[i][j] + " "); 

            else if (j == 0) 
                System.out.print(a[i][j] + " "); 
            else if (j == cols - 1) 
                System.out.print(a[i][j] + " "); 
            else
                System.out.print("  "); 
        } 
        System.out.println(""); 
    }
    System.out.println("");
   }
qmelpv7a

qmelpv7a1#

如果维数小于3,则没有中间矩阵,请尝试使用代码,

private static int[][] cropCenterPart(int[][] arr, int row, int col) {
    if (!(row > 2 && col > 2))
        return arr;
    int[][] resultArr = new int[row - 2][col - 2]; // as the first row,col and 
                                                   // last row,col is neglected
    for (int i = 1; i < row-1; i++) {
        System.arraycopy(arr[i], 1, resultArr[i - 1], 0, col - 1 - 1);
    }
    return resultArr;
}

在main函数(或从中调用的函数)中,如下打印

int resultArr[][] = cropCenterPart (arr, row, col);
for(int i = 0; i<row-2; i++) {   // here the row is the actual row size of arr
    System.out.println();
    for(int j=0; j<col-2; j++) {
        System.out.print(" " + resultArr[i][j]);
    }
}
4nkexdtk

4nkexdtk2#

答案是

public class A {

    public void extractBoundaries(int a[][],int rows,int cols){

        for (int i = 0; i < rows; i++) { 
            for (int j = 0; j < cols; j++) { 
                if (i == 0 || j == 0 || i == 3 || j == 3) 
                    System.out.print(a[i][j] + " "); 

                else
                    System.out.print("  "); 
            } 
            System.out.println(""); 
        }
        System.out.println("");
   }
    public void cropCenterPart(int a[][],int rows,int cols){

        for (int i = 0; i < rows; i++) { 
            for (int j = 0; j < cols; j++) { 
                if (i == 0 || j == 0 || i == 3 || j == 3) 
                  System.out.print("  ");
                else

                    System.out.print(a[i][j] + " ");
            } 
            System.out.println(""); 
        }
        System.out.println("");

    }
}

相关问题