Given a matrix, rotate it 90 degrees clockwise in-place.
- User
Given a matrix, rotate it 90 degrees clockwise in-place.
Assistant
To solve this problem, we need to rotate a given square matrix 90 degrees clockwise in-place. The solution involves two main steps: transposing the matrix and then reversing each row of the transposed matrix.
Approach
- Transpose the Matrix: Transposing a matrix means swapping its rows with columns. For a square matrix, this can be done in-place by swapping elements across the diagonal.
- Reverse Each Row: After transposing the matrix, reversing each row will give the final rotated matrix.
Solution Code
def rotate(matrix): n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for row in matrix: row.reverse()Explanation
-
Transposing the Matrix:
- The transpose of a matrix is obtained by swapping elements at positions (i, j) with (j, i) for all i < j. This ensures that we only swap each pair once, avoiding redundant swaps.
- For example, in a 3x3 matrix, the element at (0, 1) swaps with the element at (1, 0), and so on.
-
Reversing Each Row:
- After transposing, each row of the matrix is reversed to achieve the 90-degree rotation. This step effectively moves elements from their transposed positions to their final rotated positions.
This approach ensures that the matrix is rotated in-place with a time complexity of O(n²) and a space complexity of O(1), where n is the number of rows (and columns) in the square matrix. This is efficient as it meets the problem constraints and operates directly on the input matrix.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.