Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,959 questions

51,901 answers

573 users

How to rotate a matrix 90 degrees clockwise in Python

2 Answers

0 votes
def rotate90_clockwise(matrix):
    """Rotates a square matrix 90 degrees clockwise."""
    N = len(matrix)

    # Step 1: 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]

    # Step 2: Reverse each row
    for i in range(N):
        matrix[i].reverse()

def print_matrix(matrix):
    """Prints the matrix in a readable format."""
    for row in matrix:
        print(" ".join(map(str, row)))


matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print("Original Matrix:")
print_matrix(matrix)

rotate90_clockwise(matrix)

print("\nRotated Matrix:")
print_matrix(matrix)



'''
run:
 
Original Matrix:
1 2 3
4 5 6
7 8 9

Rotated Matrix:
7 4 1
8 5 2
9 6 3
 
'''

 



answered May 29, 2025 by avibootz
0 votes
def rotate90_clockwise(matrix):
    """Rotates a matrix 90 degrees clockwise."""
    rows, cols = len(matrix), len(matrix[0])
    rotated = [[0] * rows for _ in range(cols)]

    for i in range(rows):
        for j in range(cols):
            rotated[j][rows - 1 - i] = matrix[i][j]  # Mapping to rotated position
    
    return rotated

def print_matrix(matrix):
    """Prints the matrix in a readable format."""
    for row in matrix:
        print(" ".join(map(str, row)))

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

print("Original Matrix:")
print_matrix(matrix)

rotated = rotate90_clockwise(matrix)

print("\nRotated Matrix:")
print_matrix(rotated)



'''
run:
 
Original Matrix:
1 2 3 4
5 6 7 8
9 10 11 12

Rotated Matrix:
9 5 1
10 6 2
11 7 3
12 8 4
 
'''

 



answered May 29, 2025 by avibootz

Related questions

2 answers 138 views
2 answers 149 views
2 answers 173 views
2 answers 137 views
2 answers 129 views
...