leetcode------Rotate Image

标题: Rotate Image
通过率: 31.7%
难度: 中等

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?

这个题目想了好久想不出来,能找出来规律就是做不出来,最后参考了网上的代码和思路:

整体就是代替matrix[i][j]=matrix[len-1-j][i]

就是一个2Dmatrix中每个元素都要向右移动N-1次,只用对半移动然后是一层一层的移动,

1 2 3
4 5 6
7 8 9

1-》3-》9-》7-》1

2-》6-》8-》4-》2

上述是第一层第二层只有5不用移动

一次类推

所以移动的层数等于数组的层数除以2,

不管N是个多大的数字,每一层额每一个位置都是四个数字的转换,这就有了规律

具体看代码:

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         int len=matrix.length;
 4         for(int round=0;round<len/2;round++){
 5             int i=round;
 6             for(int j=i;j<len-round-1;j++){
 7                 int tmp=matrix[i][j];
 8                     int temp = matrix[i][j];
 9                     matrix[i][j] = matrix[len-j-1][i];
10                     matrix[len-j-1][i] = matrix[len-i-1][len -j -1];
11                     matrix[len-i-1][len -j -1] = matrix[j][len - i -1];
12                     matrix[j][len - i -1] = temp;
13                 
14             }
15         }
16     }
17 }
原文地址:https://www.cnblogs.com/pkuYang/p/4320490.html