【原創】48. Rotate Image ---leetcode算法筆記

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?

思路:順時針旋轉90度,即將數組繞其中心順時針旋轉90度。問題關鍵在找到數組元素旋轉後的座標位置。可以通過座標變換將座標原點變換到數組中心處(數組本身的座標原點可以看作在0行0列處),這樣數組繞原點旋轉90度即可。空間複雜度爲O(1)。

代碼:

public void rotate(int[][] matrix) {
        int n = matrix.length ;
        if(n <= 1) return ;
        float center = (float)(n-1)/2;
        int x , y ;
        int r , c ;
        int buffer , temp;
        for(int i = 0 ;i <= center ;i ++){
            for(int j = 0 ;j < center ;j ++){
                r = j ;
                c = i ;
                buffer = matrix[c][r] ;
                for(int k = 0 ;k < 4 ;k ++){
                    // x = r - center ;
                    // y = c - center ;
                    // x =  -y ;
                    // y =  x ;
                    // x = x + center ;
                    // y = y + center ;
                    
                    x = (int)(2*center) - c ;
                    y =  r ;
                    
                    temp = matrix[y][x] ;
                    matrix[y][x] = buffer ;
                    buffer = temp ;
                    
                    r = x ;
                    c = y ;
                }
            }
        }

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章