- The rotate function takes a 2D matrix as input and rotates it in place by 90 degrees clockwise.
- const n = matrix.length;: We calculate the size of the matrix (n x n) since it’s a square matrix.
- for (let layer = 0; layer < Math.floor(n / 2); layer++): We iterate through each layer of the matrix. We only need to go up to the middle layer (rounded down if n is odd) because the rest of the layers will be rotated along with the outer layers.
- const first = layer; const last = n – 1 – layer;: We define variables first and last to represent the indices of the first and last elements in the current layer.
- The inner loop starts with i at first and continues until i reaches last – 1.
- const offset = i – first; const top = matrix[first][i];: We calculate the offset to move from the current position i to the starting position first, and we store the value of the top element in the current layer in the variable top.
- matrix[first][i] = matrix[last – offset][first];: We move the left element to the top position.
- matrix[last – offset][first] = matrix[last][last – offset];: We move the bottom element to the left position.
- matrix[last][last – offset] = matrix[i][last];: We move the right element to the bottom position.
- matrix[i][last] = top;: We move the top element to the right position, completing the rotation of the current four elements.
- The process repeats for the entire layer, rotating all the elements in that layer.
- Once all the layers have been rotated, the function completes, and the matrix is now rotated 90 degrees clockwise in place.