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

Rotate Image

时间:2015-03-12 09:54:15      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二维数组   算法   java   

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/44216867


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?


思路:

(1)题意为给定一个n*n的矩阵代表一幅图像,求将其顺时针旋转90度后所得矩阵。

(2)该题主要考察对二维数组的操作。n*n的矩阵显然是一个正方形,其实可对该题进行扩展为任意m*n的矩形,效果差不多。将n*n的矩阵形式化为一个n*n的二维数组,对二维数组的旋转就转化为对二维数组中元素位置的调整了,通过对比发现转换前后对应关系为:result[i][j] = matrix[row-1-j][i],其中result为新创建的数组用于存储转换后的
元素,matrix为目标数组。需要注意的是,得到result数组后还需将其中的元素赋值到原始数组中,才能达到对原始数组的旋转。详情见下方代码。

(3)希望本文对你有所帮助。


算法代码实现如下:

	/**
	 * @author liqqc
	 * @param matrix
	 * @return
	 */
    public static int[][]  rotate(int[][] matrix) {
        
    	if(matrix.length==0 ||matrix[0].length==0){
    		return null;
    	}
    	
    	int row = matrix.length;
    	int col = matrix[0].length;
    	
    	
    	int[][] result = new int[row][col];
    	
    	//第一行变为最后一列
    	for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				result[i][j] = matrix[row-1-j][i];
			}
		}
    	
    	for (int i = 0; i < result.length; i++) {
			for (int j = 0; j < result.length; j++) {
				matrix[i][j] = result[i][j];
			}
		}
    	return matrix;
    }




Rotate Image

标签:leetcode   二维数组   算法   java   

原文地址:http://blog.csdn.net/pistolove/article/details/44216867

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