|
| 1 | +/* |
| 2 | + Rotate Image (LeetCode #48) |
| 3 | +
|
| 4 | + - You are given an n x n 2D matrix representing an image, rotate the |
| 5 | + image by 90 degrees (clockwise). |
| 6 | + - You have to rotate the image in-place, which means you have to modify |
| 7 | + the input 2D matrix directly. DO NOT allocate another 2D matrix and do |
| 8 | + the rotation. |
| 9 | +
|
| 10 | + Example 1: |
| 11 | +
|
| 12 | + 1 2 3 7 4 1 |
| 13 | + 4 5 6 ---> 8 5 2 |
| 14 | + 7 8 9 9 6 3 |
| 15 | +
|
| 16 | + - Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
| 17 | + - Output: [[7,4,1],[8,5,2],[9,6,3]] |
| 18 | +
|
| 19 | + Example 2: |
| 20 | +
|
| 21 | + 5 1 9 11 15 13 2 5 |
| 22 | + 2 4 8 10 ---> 14 3 4 1 |
| 23 | + 13 3 6 7 12 6 8 9 |
| 24 | + 15 14 12 16 16 7 10 11 |
| 25 | +
|
| 26 | + - Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] |
| 27 | + - Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] |
| 28 | +
|
| 29 | + Constraints: |
| 30 | + - n == matrix.length == matrix[i].length |
| 31 | + - 1 <= n <= 20 |
| 32 | + - -1000 <= matrix[i][j] <= 1000 |
| 33 | +*/ |
| 34 | + |
| 35 | +/* |
| 36 | + Solution: |
| 37 | +
|
| 38 | + 1. First, take the transpose of the matrix |
| 39 | + - Example: |
| 40 | + 1 2 3 1 4 7 |
| 41 | + 4 5 6 ---> 2 5 8 |
| 42 | + 7 8 9 3 6 9 |
| 43 | +
|
| 44 | + 2. Second, flip the matrix horizontally |
| 45 | + - Example: |
| 46 | + 1 4 7 7 4 1 |
| 47 | + 2 5 8 ---> 8 5 2 |
| 48 | + 3 6 9 9 6 3 |
| 49 | +
|
| 50 | + 3. Problem solved! |
| 51 | +
|
| 52 | + - Solution is O(n) where n is the size (total number of entries) of the |
| 53 | + input matrix |
| 54 | +*/ |
| 55 | + |
| 56 | +function rotateImage(matrix) { |
| 57 | + const n = matrix.length; |
| 58 | + |
| 59 | + // take transpose |
| 60 | + for (let i = 0; i < n; i++) { |
| 61 | + for (let j = i; j < n; j++) { |
| 62 | + const temp = matrix[i][j]; |
| 63 | + matrix[i][j] = matrix[j][i]; |
| 64 | + matrix[j][i] = temp; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + // flip horizontally |
| 69 | + for (let i = 0; i < n; i++) { |
| 70 | + let left = 0; |
| 71 | + let right = n - 1; |
| 72 | + |
| 73 | + while (left < right) { |
| 74 | + const temp = matrix[i][left]; |
| 75 | + matrix[i][left] = matrix[i][right]; |
| 76 | + matrix[i][right] = temp; |
| 77 | + left++; |
| 78 | + right--; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +module.exports = { rotateImage }; |
0 commit comments