LeetCode – 48. Rotate Image

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

Rotate the image by 90 degrees (clockwise).

This problem seems complicated, but it's actually just about switching arrays. However, it's not very easy to implement and requires very careful operation.

I solved this problem using JavaScript before, and the method I used was rather clever. It involved finding a pattern and then modifying it (I suspect many people won't understand this), so I'll post it here first.

/** * @param {number[][]} matrix * @return {void} Do not return anything, modify matrix in-place instead. */ var rotate = function(matrix) { var res = JSON.parse(JSON.stringify(matrix)); n = matrix.length; if(matrix.length == 0 || matrix.length != matrix[0].length){ return false; } for(i=0;i-1;j--){ matrix[i][n-j-1] = res[j][i]; } } };

There are basically two solutions to this problem online: swapping the diagonals and peeling back the layers like an onion. The former requires less code, but it's easy to get stuck. The latter is clearer and easier to understand; if you can't figure it out during an interview, just draw a diagram and you'll have the solution.

public class Solution { public void rotate(int[][] matrix) { int layer = matrix.length /2; for(int i=0;i 

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「LeetCode – 48. Rotate Image」

151
0 0 151

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top