首页 > 代码库 > LeetCode: Rotate Image 解题报告

LeetCode: Rotate Image 解题报告

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?

 

SOLUTION 1:

我们可以把它当作多个嵌套的环来处理,一环加一环。从外环处理到内环。为了方便处理各种下标,我们定义top, bottom, left, right来限制环的左右上下边界。

1. 令tmp = 上边界

2. 上边等于左边元素

3. 左边等于下边元素

4. 下边等于右边元素

5. 右边等于上边元素(tmp)

使用n来记录每一圈的边长。一圈进行4次操作,每次操作移动n - 1个元素即可。

 1 public class Solution { 2     public void rotate(int[][] matrix) { 3         if (matrix == null || matrix.length == 0  4            || matrix[0].length == 0) { 5             return;        6         } 7          8         int n = matrix.length; 9         int top = 0, down = n - 1, left = 0, right = n - 1;10         11         while (n > 1) {12             for (int i = 0; i < n - 1; i++) {13                 int tmp = matrix[top][left + i];14                 // 另上边等于左边15                 matrix[top][left + i] = matrix[down - i][left];16                 17                 // 另左边等于下边18                 matrix[down - i][left] = matrix[down][right - i];19                 20                 // 另下边等于右边21                 matrix[down][right - i] = matrix[top + i][right];22                 23                 // 另右边等于上边24                 matrix[top + i][right] = tmp;25             }26             top++;27             right--;28             left++;29             down--;30             31             n -= 2;32         }33         34         return;35     }36 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/array/Rotate.java

LeetCode: Rotate Image 解题报告