Rotate Matrix by 90 Degrees
Understanding the Problem
The goal is to rotate a given square matrix by 90 degrees clockwise.
Method 1: Using a Temporary Matrix
This method uses a temporary matrix to store the rotated values.
def rotate_matrix(matrix): n = len(matrix) temp = [[0] * n for _ in range(n)] # Store the rotated values in a temporary matrix for i in range(n): for j in range(n): temp[j][n - 1 - i] = matrix[i][j] # Copy the temporary matrix back to the original matrix for i in range(n): for j in range(n): matrix[i][j] = temp[i][j] def print_matrix(matrix): for row in matrix: print(" ".join(map(str, row))) # Example usage matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] rotate_matrix(matrix) print("Rotated Matrix:") print_matrix(matrix)
Output:
Rotated Matrix: 7 4 1 8 5 2 9 6 3
Method 2: In-Place Rotation
This method rotates the matrix in place without using extra space.
def rotate_matrix(matrix): n = len(matrix) # Transpose the matrix for i in range(n): for j in range(i, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] # Reverse each row for i in range(n): matrix[i].reverse() def print_matrix(matrix): for row in matrix: print(" ".join(map(str, row))) # Example usage matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] rotate_matrix(matrix) print("Rotated Matrix:") print_matrix(matrix)
Output:
Rotated Matrix: 7 4 1 8 5 2 9 6 3
Method 3: Using Layer by Layer Rotation
This method rotates the matrix layer by layer.
def rotate_matrix(matrix): n = len(matrix) for layer in range(n // 2): first = layer last = n - 1 - layer for i in range(first, last): offset = i - first # Save the top element top = matrix[first][i] # Move left element to top matrix[first][i] = matrix[last - offset][first] # Move bottom element to left matrix[last - offset][first] = matrix[last][last - offset] # Move right element to bottom matrix[last][last - offset] = matrix[i][last] # Assign top element to right matrix[i][last] = top def print_matrix(matrix): for row in matrix: print(" ".join(map(str, row))) # Example usage matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] rotate_matrix(matrix) print("Rotated Matrix:") print_matrix(matrix)
Output:
Rotated Matrix: 7 4 1 8 5 2 9 6 3