Saturday, July 09, 2016

Rotate Matrix 90 degrees

I had an elder post at http://mashijie.blogspot.ca/2015/06/rotating-nxn-matrix-90-degrees.html.
That is not as concise as this solution:
in order to rotate, flip it Diagonally, then vertically.

What to learn: diagonally swapping.




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Solution {
    void swap(int[][] matrix,int x, int y,int x1,int y1){
       /* a=a^b;
        b=a^b;
        a=a^b;*/
        int tmp = matrix[x][y];
        matrix[x][y]=matrix[x1][y1];
        matrix[x1][y1]=tmp;
        
    }
    public void rotate(int[][] matrix) {
          int len = matrix[0].length;
          //flip Diagonally
          for(int i =0; i<len-1; i++)  
          {  
            for(int j=0;j<len-i;j++)  
            {  
              swap(matrix,i,j, len-1-j,len-1-i);  
            }  
          } 
          //vertically
        for(int i =0; i<len/2; i++)  
        {  
         for(int j=0;j<len;j++){ 
              swap(matrix,i,j, len-i-1,j);  
            }  
        } 
    }
}

No comments: