Rotate Image 161

Question

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).

Example

Given a matrix

[ [1,2], [3,4] ]

rotate it by 90 degrees (clockwise), return

[ [3,1], [4,2] ]

Challenge

Do it in-place.

Solution

思想很简单,就是左上和右上换,右上和右下换,右下和左下换,左下和左上换。每次从4个角开始换起,用count记录从matrix往里的步数。index可能稍微麻烦一些,需要记住上下是行不变列变,左右是列不变行变,不变的和count相关,变化的和i相关。

代码如下:

public class Solution {
    /**
     * @param matrix: A list of lists of integers
     * @return: Void
     */
    public void rotate(int[][] matrix) {
        // write your code here
        if(matrix == null || matrix.length == 0){
            return;
        }

        int n = matrix.length;
        int count = 0;
        while(count < n - 1 - count){
            for(int i = count; i < n - count - 1; i++){
                int temp = matrix[count][i];
                matrix[count][i] = matrix[n - 1 - i][count];
                matrix[n - 1 - i][count] = matrix[n - 1 - count][n - 1 - i];
                matrix[n - 1 - count][n - 1 - i] = matrix[i][n - 1 - count];
                matrix[i][n - 1 - count] = temp;
            }
            count++;
        }
    }
}

results matching ""

    No results matching ""