[leetcode]48RotateImage二维数组翻转

import java.util.Arrays;

/**
 * You are given an n x n 2D matrix representing an image.

 Rotate the image by 90 degrees (clockwise).

 Follow up:
 Could you do this in-place?

翻转二维数组,思路是把数组分成length/2层,每层分别翻转,左边的到上边,下边的到左边,右边的到下边,上边的到右边
 每层也有一个循环,设置一个中间量,这层的数一个一个交换,注意每层循环的次数(就是这层每条边的数量-1)
 */
public class Q48RotateImage {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}};
        rotate(matrix);
        for (int[] num :
                matrix) {
            System.out.println(Arrays.toString(num));
        }

    }
    public static void rotate(int[][] matrix) {
        int temp;
        int l = matrix.length;
        for (int i = 0; i < l / 2; i++) {
            for (int j = 0; j < l-1-(2*i); j++) {
                temp = matrix[i][i+j];
                matrix[i][i+j] = matrix[l-1-i-j][i];
                matrix[l-1-i-j][i] = matrix[l-1-i][l-1-i-j];
                matrix[l-1-i][l-1-i-j] = matrix[i+j][l-1-i];
                matrix[i+j][l-1-i] = temp;
            }
        }
    }
}

 

posted @ 2017-07-04 17:21  stAr_1  阅读(208)  评论(0编辑  收藏  举报