Title: Rotate Image Source: leetcode.com
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?
Java solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
/* https://leetcode.com/problems/rotate-image/ */ class RotateImage { public static void main(String args[]) { int[][] image = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; printMatrix(image); RotateImage solution = new RotateImage(); solution.rotate(image); printMatrix(image); } public void rotate(int[][] image) { int layer = image.length/2; for(int j=0;j<layer;j++) { int length = image.length-1-(2*j); System.out.println("layer: "+j + " length: "+length); for(int i=0;i<length;i++) { System.out.println("i: "+i); int temp = image[j][i]; //left-bottom -> left-top image[j][i] = image[length-i][j]; //printMatrix(image); //right-bottom -> left-bottom image[length-i][j] = image[length][length-i]; //printMatrix(image); //top-right -> right-bottom image[length][length-i] = image[i][length]; //printMatrix(image); //top-left -> top-right image[i][length] = temp; } printMatrix(image); } } static void printMatrix(int[][] image) { for(int[] row: image) { for(int num:row) { System.out.print(num+"\t"); } System.out.println(); } System.out.println(); } } |
Python solution
(Not an in place solution)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
''' https://leetcode.com/problems/rotate-image/ ''' class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ n = len(matrix) if n == 1: return cm = [] for lst in matrix: cm.append([i for i in lst]) for i in range(n): for j in range(n): matrix[j][n-i-1] = cm[i][j] |