码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Rotate Image

时间:2014-11-20 13:20:00      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   on   

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 }

 

Leetcode-Rotate Image

标签:style   blog   io   ar   color   os   sp   for   on   

原文地址:http://www.cnblogs.com/lishiblog/p/4110237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!