搜索此博客

2013年1月15日星期二

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?

I have been asked this question once in an interview. And I was required that only swap operations are allowed. Here is my solution:

01 public void rotate(int[][] matrix) {
02     int n=matrix.length;
03     for(int i=0;i<n/2;i++)
04     {
05         for(int j=i;j<n-1-i;j++)
06         {
07             swap(matrix,i,j,j,n-1-i);
08             swap(matrix,n-1-j,i,n-1-i,n-1-j);
09             swap(matrix,i,j,n-1-i,n-1-j);
10         }
11     }
12 }
13 
14 public void swap(int[][] matrix, int i1, int j1, int i2, int j2)
15 {
16     int temp=matrix[i1][j1];
17     matrix[i1][j1]=matrix[i2][j2];
18     matrix[i2][j2]=temp;
19 }

没有评论:

发表评论