본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

Rotating a 2D Array by 90 Degrees - In Place (Java)

A 2-dimensional array is an array of arrays.

Implement a function that takes a square 2D array (# columns = # rows) and rotates it by 90 degrees.

Example: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

->

[[7, 4, 1], [8, 5, 2], [9, 6, 3]]

When you are done, try implementing this function so that you can solve this problem in place. Solving it in place means that your function won't create a new array to solve this problem.  Instead, modify the content of the given array with O(1) extra space.


풀이


강의를 들었는데 사실 수도 코드 설명을 듣고 작성하기가 쉽지가 않았다...


이해력이 부족한듯 한데 좀 더 나중에 찬찬히 읽어봐야 할 듯

public class R2InPlace {

    public static void main(String[] args) {

        // NOTE: The following input values will be used for testing your solution.

        int a1[][] = {{1, 2, 3},

                      {4, 5, 6},

                      {7, 8, 9}};

        // rotate(a1, 3) should return:

        // [[7, 4, 1],

        //  [8, 5, 2],

        //  [9, 6, 3]]


        int a2[][] = {{1, 2, 3, 4},

                      {5, 6, 7, 8},

                      {9, 10, 11, 12},

                      {13, 14, 15, 16}};

        // rotate(a2, 4) should return:

        // [[13, 9, 5, 1],

        //  [14, 10, 6, 2],

        //  [15, 11, 7, 3],

        //  [16, 12, 8, 4]]

    }


    // Implement your solution below.

    public static int[][] rotate(int[][] a, int n) {

        // n/2 gives us floor(n/2)

        // and n/2 + n%2 gives us ceiling(n/2)

        for (int i = 0; i < n / 2 + n % 2; i++) {

            for (int j = 0; j < n / 2; j++) {

                int[] tmp = new int[4];

                int currentI = i;

                int currentJ = j;

                for (int k = 0; k < 4; k++) {

                    tmp[k] = a[currentI][currentJ];

                    int[] newCoordinates = rotateSub(currentI, currentJ, n);

                    currentI = newCoordinates[0]; currentJ = newCoordinates[1];

                }

                for (int k = 0; k < 4; k++) {

                    a[currentI][currentJ] = tmp[(k + 3) % 4];

                    int[] newCoordinates = rotateSub(currentI, currentJ, n);

                    currentI = newCoordinates[0]; currentJ = newCoordinates[1];

                }

            }

        }

        return a;

    }


    public static int[] rotateSub(int i, int j, int n) {

        int[] newCoordinates = new int[2];

        newCoordinates[0] = j;

        newCoordinates[1] = n - 1 - i;

        return newCoordinates;

    }

 }