How do you rotate a two dimensional array?

后端 未结 30 3090
耶瑟儿~
耶瑟儿~ 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:30

    Here is the Java version:

    public static void rightRotate(int[][] matrix, int n) {
        for (int layer = 0; layer < n / 2; layer++) {
            int first = layer;
            int last = n - 1 - first;
            for (int i = first; i < last; i++) {
               int offset = i - first;
               int temp = matrix[first][i];
               matrix[first][i] = matrix[last-offset][first];
               matrix[last-offset][first] = matrix[last][last-offset];
               matrix[last][last-offset] = matrix[i][last];
               matrix[i][last] = temp;
            }
        }
    }
    

    the method first rotate the mostouter layer, then move to the inner layer squentially.

提交回复
热议问题