Rotate Image

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?

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 5         int dep = 0;
 6         int len = matrix.length - 1;
 7         int start = 0;
 8         int end = matrix.length - 1;
 9         while(start <= end)
10         {
11             int cur = 0;
12             for(int i = start; i < end; i ++){
13                 cur = matrix[dep][i];
14                 matrix[dep][i] = matrix[len - i][dep];
15                 matrix[len - i][dep] = matrix[len - dep][len - i];
16                 matrix[len - dep][len - i] = matrix[i][len - dep];
17                 matrix[i][len - dep] = cur;
18             }
19             start ++;
20             end --;
21             dep += 1;
22         }
23     }
24 }

 第三遍:

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
 4         int top = 0, bot = matrix.length - 1, len = matrix.length - 1;
 5         while(top < bot){
 6             for(int i = top; i < bot; i ++){
 7                 int tmp = matrix[top][i];
 8                 matrix[top][i] = matrix[len - i][top];
 9                 matrix[len - i][top] = matrix[bot][len - i];
10                 matrix[bot][len - i] = matrix[i][bot];
11                 matrix[i][bot] = tmp;
12             }
13             top ++;  bot --; 
14         }
15     }
16 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3358436.html