• + 0 comments

    intuitive and short solution.

    def matrixRotation(matrix, r): new_matrix = [[0] * n for _ in range(m)] # Init new matrix

        # Solve it like onion, first start with the outside then dive one layer inside.
    for k in range(min(m, n) // 2):
                # Creating rotation path. Values are indices (row, col)
        pos = [(i, k) for i in range(k, m - k)]
        pos.extend([(m - 1 - k, i) for i in range(1 + k, n - k)])
        pos.extend([(i, n - 1 - k) for i in range(m - 2 - k, -1 + k, -1)])
        pos.extend([(k, i) for i in range(n - 2 - k, k, -1)])
    
        length = len(pos)
        for i in range(len(pos)):
                        # Find correct index after rotation. 
            idx = (i - r) % length
            new_matrix[pos[i][0]][pos[i][1]] = matrix[pos[idx][0]][pos[idx][1]]
    # Print the result.       
    for i in range(m):
        print(' '.join(map(str, new_matrix[i])))