How do you rotate a two dimensional array?

后端 未结 30 3747
耶瑟儿~
耶瑟儿~ 2020-11-22 02:43

Inspired by Raymond Chen\'s post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I\'d

30条回答
  •  我在风中等你
    2020-11-22 03:27

    You can do this in 3 easy steps:

    1)Suppose we have a matrix

       1 2 3
       4 5 6
       7 8 9
    

    2)Take the transpose of the matrix

       1 4 7
       2 5 8
       3 6 9
    

    3)Interchange rows to get rotated matrix

       3 6 9
       2 5 8
       1 4 7
    

    Java source code for this:

    public class MyClass {
    
        public static void main(String args[]) {
            Demo obj = new Demo();
            /*initial matrix to rotate*/
            int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
            int[][] transpose = new int[3][3]; // matrix to store transpose
    
            obj.display(matrix);              // initial matrix
    
            obj.rotate(matrix, transpose);    // call rotate method
            System.out.println();
            obj.display(transpose);           // display the rotated matix
        }
    }
    
    class Demo {   
        public void rotate(int[][] mat, int[][] tran) {
    
            /* First take the transpose of the matrix */
            for (int i = 0; i < mat.length; i++) {
                for (int j = 0; j < mat.length; j++) {
                    tran[i][j] = mat[j][i]; 
                }
            }
    
            /*
             * Interchange the rows of the transpose matrix to get rotated
             * matrix
             */
            for (int i = 0, j = tran.length - 1; i != j; i++, j--) {
                for (int k = 0; k < tran.length; k++) {
                    swap(i, k, j, k, tran);
                }
            }
        }
    
        public void swap(int a, int b, int c, int d, int[][] arr) {
            int temp = arr[a][b];
            arr[a][b] = arr[c][d];
            arr[c][d] = temp;    
        }
    
        /* Method to display the matrix */
        public void display(int[][] arr) {
            for (int i = 0; i < arr.length; i++) {
                for (int j = 0; j < arr.length; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    

    Output:

    1 2 3 
    4 5 6 
    7 8 9 
    
    3 6 9 
    2 5 8 
    1 4 7 
    

提交回复
热议问题