Saturday, October 3, 2015

[1.6] Rotate an umage by 90 degrees

1. Example

123
456
789

==>

741
852
963


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
==>


NOTE: do it in place

2. Implementation


public void rotate(int[][] matrix, int n)
{



     // vlaidate the input
     if ( matrix == null || matrix.length ==0 || matrix[0].length == 0)
     {
           return matrix;
     }

  


     // 
     for ( int i = 0 ; i < n/2 ; i++)
     {
            for ( int j = i ; j < n -1 ; j++ )
            {
                  int tmp = matrix[i][j];//top
                  matrix[i][j] = matrix[n-1-j][i];//top<-left
                  matrix[n-1-j][i] = matrix[n-1-i][n-1-j];//left<-bottom
                  matrix[n-1-i][n-1-j] = matrix[j][n-1-i];//bottom<-right
                  matrix[j][n-1-i] = tmp;// right<-top
            }
     }





}      
3. Similar Ones

No comments:

Post a Comment