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?
Have you met this question in a real interview?
Analysis:
We can rotate the outest circle of the matrix, and then move to the next inner circle. I used a recursive method.
Solution:
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 int len = matrix.length; 4 rotateRecur(matrix,0,0,len); 5 6 } 7 8 public void rotateRecur(int[][] matrix, int curX, int curY, int len){ 9 if (len==1 || len==0) return; 10 11 for (int i=0;i<len-1;i++){ 12 int temp = matrix[curX][curY+i]; 13 matrix[curX][curY+i] = matrix[curX+len-1-i][curY]; 14 matrix[curX+len-1-i][curY] = matrix[curX+len-1][curY+len-1-i]; 15 matrix[curX+len-1][curY+len-1-i] = matrix[curX+i][curY+len-1]; 16 matrix[curX+i][curY+len-1] = temp; 17 } 18 rotateRecur(matrix,curX+1,curY+1,len-2); 19 } 20 21 }
Solution2:
We can easily write the method into iterative method.
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 int mLen = matrix.length; 4 5 for (int j=0;j<mLen/2;j++){ 6 int curX = j; 7 int curY = j; 8 int len = mLen-j*2; 9 10 for (int i=0;i<len-1;i++){ 11 int temp = matrix[curX][curY+i]; 12 matrix[curX][curY+i] = matrix[curX+len-1-i][curY]; 13 matrix[curX+len-1-i][curY] = matrix[curX+len-1][curY+len-1-i]; 14 matrix[curX+len-1][curY+len-1-i] = matrix[curX+i][curY+len-1]; 15 matrix[curX+i][curY+len-1] = temp; 16 } 17 18 } 19 20 } 21 }