如何将矩阵的最后一个值作为第一个值,反之亦然

时间:2014-11-23 19:51:19

标签: java matrix reverse

伙计们,我一直试图将矩阵的最后一个值作为第一个,第一个值作为第二个,但这是我的出来

生成矩阵es:

8, 4, 10, 
4, 6, 9, 
3, 9, 7,

颠倒矩阵: 7,9,3,7,9,3,7,9,3,

这是代码:

public String segmat(int a[][]) {
    String s = "";
    for (int i =0;i<a.length;i++){
    //for (int i = a.length - 1; i >= 0; i--) {
        for (int j = a[0].length - 1; j >= 0; j--) {
            s += a[a.length - 1][j] + ", ";
        }
    }
    return s;
}

1 个答案:

答案 0 :(得分:0)

此示例对您有所帮助

我对代码进行了评论,因此很容易理解

public class MatrixExample {

    private static int[][] reverse(int[][] matrix){
        int row=matrix.length;
        int column=matrix[0].length; //we have for shure this element, his length is the number of colmn
        int to_return[][] = new int[row][column]; //this is a matrix of the same dimention of the original
        //the indexes that will cicle the row and the column of the new matrix
        int new_row=0; 
        int new_column=0;
        for(int i=row-1;i>-1;i--){ //this will cile the rows from the last to thee first
            for(int j=column-1;j>-1;j--){  //this will cicle the colums from the last to the first
                to_return[new_row][new_column]=matrix[i][j];
                new_column++;
            }
            new_column=0;
            new_row++;
        }
        return to_return;
    }
    public static void main(String[] args) {
        int matrix[][] = {{ 1, 2, 3},
                        {4, 5, 6},
                        {7, 8, 9},
                        {10,11,12}};

        int[][] new_matrix = reverse(matrix);

        for(int i=0;i<new_matrix.length;i++){
            for(int j=0;j<new_matrix[0].length;j++){
                System.out.print(new_matrix[i][j]+" ");
            }
            System.out.println();
        }
    }

}