【leetcode】48. Rotate Image

来源:互联网 发布:淘宝消字灵是真的么 编辑:程序博客网 时间:2024/05/29 08:20

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).(将二维数组顺时针翻转90度)

Follow up:
Could you do this in-place?

Subscribe to see which companies asked this question

The idea was firstly transpose the matrix and then flip it symmetrically.(先转置,再水平翻转) For instance,

1  2  3             4  5  67  8  9

after transpose, it will be swap(matrix[i][j], matrix[j][i])

1  4  72  5  83  6  9

Then flip the matrix horizontally. (swap(matrix[i][j], matrix[i][matrix.length-1-j])

7  4  18  5  29  6  3
数组名.length指示数组的行数。数组名[行下标] .length指示该行中的元素个数。
public class Solution {    public void rotate(int[][] matrix) {        for(int i = 0; i<matrix.length; i++){            for(int j = i; j<matrix[0].length; j++){                int temp = 0;                temp = matrix[i][j];                matrix[i][j] = matrix[j][i];                matrix[j][i] = temp;            }        }        for(int i =0 ; i<matrix.length; i++){            for(int j = 0; j<matrix.length/2; j++){                int temp = 0;                temp = matrix[i][j];                matrix[i][j] = matrix[i][matrix.length-1-j];                matrix[i][matrix.length-1-j] = temp;            }        }    }}
同理  若将二维数组逆时针翻转90度,则先将数组转置,再将数组在垂直方向翻转。
0 0
原创粉丝点击