LeetCode 48. Rotate Image

参考资料:左程云的算法课

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

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

思路:先对最外层框做下标连续推(这个词借鉴了左老师的书),然后次外层,。。。
比如最外层第一个下标位置的下标连续推,应该是 1 去 3的位置, 3 去 9 的位置,。。。。
LeetCode 48. Rotate Image_第1张图片
比如最外层第2个下标位置的下标连续推
LeetCode 48. Rotate Image_第2张图片

class Solution {
    public void rotate(int[][] ma) {
        int n=ma.length;
        int r1=0,r2=n-1;

        while(r1<r2)
        {
            rotateFrame(ma,r1,r1,r2,r2); // 转个框
            r1++;
            r2--;
        }
    
    }

    public void rotateFrame(int[][] ma, int r1, int c1, int r2, int c2)
    {
        for(int i=0;i<c2-c1;i++)
        {
            int t = ma[r1+i][c2];
            ma[r1+i][c2] = ma[r1][c1+i];

            ma[r1][c1+i] = ma[r2][c2-i];
            ma[r2][c2-i] = t;

            t= ma[r2-i][c1];
            ma[r2-i][c1] = ma[r1][c1+i];
            ma[r1][c1+i]=t;

        }
    }
}

你可能感兴趣的:(数据结构与算法,leetcode,算法)