You are given a square matrix. Write an algorithm that shifts each element in the matrix one position clockwise. For example, the element in the top-left corner should move to the top-right corner.
We'll work with the edges of each layer: top, right, bottom, and left.
Start at the top edge (left to right). Swap the value in each position with the value stored in a temporary variable called "prev". Initially, "prev" holds the value from the second row of the leftmost column. After processing the top edge, move to the right edge (top to bottom), bottom (right to left), and left (bottom to top). Continue swapping values with "prev" as you move along each edge.
Repeat this process for every layer of the matrix, working your way inwards.
matrix = [ [ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 10, 1, 3 ], [ -4, -1, 1, 7, -6 ] ] h = len(matrix) w = len(matrix[0]) top = 0 bottom = h - 1 left = 0 right = w - 1 while (top < bottom and left < right): prev = matrix[top + 1][left] for i in range(left, right + 1): curr = matrix[top][i] matrix[top][i] = prev prev = curr top += 1 for i in range(top, bottom + 1): curr = matrix[i][right] matrix[i][right] = prev prev = curr right -= 1 for i in range(right, left - 1, -1): curr = matrix[bottom][i] matrix[bottom][i] = prev prev = curr bottom -= 1 for i in range(bottom, top - 1, -1): curr = matrix[i][left] matrix[i][left] = prev prev = curr left += 1 print(matrix)
const matrix = [ [ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 10, 1, 3 ], [ -4, -1, 1, 7, -6 ] ]; const h = matrix.length; const w = matrix[0].length; let top = 0, bottom = h - 1, left = 0, right = w - 1; while (top < bottom && left < right) { let prev = matrix[top + 1][left]; for (let i = left; i < right + 1; i++) { let curr = matrix[top][i]; matrix[top][i] = prev; prev = curr; } top++; for (let i = top; i < bottom + 1; i++) { let curr = matrix[i][right]; matrix[i][right] = prev; prev = curr; } right--; for (let i = right; i >= left; i--) { let curr = matrix[bottom][i]; matrix[bottom][i] = prev; prev = curr; } bottom--; for (let i = bottom; i >= top; i--) { let curr = matrix[i][left]; matrix[i][left] = prev; prev = curr; } left++; } console.log(matrix);