Rotating a matrix by 90 degrees clockwise is a common problem in computer science and technical interviews. This problem can be particularly interesting because the goal is to perform the rotation in place, without using additional memory for a new matrix. In this guide, we will explore how to achieve this with a clear explanation and example code.
You are given an n x n 2D matrix A representing an image. Your task is to rotate the image clockwise at 90 degrees in place. If you use an additional array, you will only receive partial credit.
1≤n≤1000
A 2D matrix A of integers
The 2D rotated matrix
[ [1, 2], [3, 4] ]
[ [3, 1], [4, 2] ]
After rotating the matrix by 90 degrees:
Here’s a JavaScript function to perform the rotation:
function rotateMatrix(A) { const n = A.length; // Step 1: Transpose the matrix for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { let temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Step 2: Reverse each row for (let i = 0; i < n; i++) { A[i].reverse(); } return A; } // Example usage: let matrix = [ [1, 2], [3, 4] ]; console.log(rotateMatrix(matrix));
Rotating a matrix in place is a valuable skill that showcases your understanding of array manipulation and in-place algorithms. By transposing the matrix and then reversing each row, you can achieve the desired rotation without using extra space. Practice this method to enhance your problem-solving abilities in technical interviews and coding challenges.
The above is the detailed content of Effortlessly Rotate a Matrix in Place: A Comprehensive Guide. For more information, please follow other related articles on the PHP Chinese website!