zoukankan      html  css  js  c++  java
  • Leetcode-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?

    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 }
  • 相关阅读:
    出队列操作
    出队列操作
    栈和队列7 数据结构和算法29
    KE上传图片
    asp.net常用快捷键
    基于jquery框架实现以下行的向上、向下和删除
    each的用法积累
    JTemplate使用2
    kindeditor API ,kindeditor使用手册,kindeditor函数,kindeditor使用,超级大收集(转载)
    线上帮助
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4110237.html
Copyright © 2011-2022 走看看