矩阵操作试题(C++/Python)——矩阵元素顺时针旋转

时间:2022-07-24
本文章向大家介绍矩阵操作试题(C++/Python)——矩阵元素顺时针旋转,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

0. 前言

给出一个矩阵,顺时针旋转他的元素,输入以及要求输出如下: e.g.0.1 示例1 3*3矩阵

Input
1    2    3
4    5    6
7    8    9

Output:
4    1    2
7    5    3
8    9    6

e.g.0.2 示例2 4*4矩阵

Input:
1    2    3    4    
5    6    7    8
9    10   11   12
13   14   15   16

Output:
5    1    2    3
9    10   6    4
13   11   7    8
14   15   16   12

1. 程序C++版

Code.1.1 示例程序

//
//  main.cpp
//  matrix_cpp
//
//  Created by CyMobius on 2018/12/4.
//  Copyright © 2018 Congying Wang. All rights reserved.
//

// C++ program to rotate a matrix
#include <iostream>
#define R 4
#define C 4
using namespace std;

void rotatematrix(int m, int n, int mat[R][C])
{
    int row = 0, col = 0;
    int prev, curr;
    
    while (row < m && col < n)
    {
        
        if (row + 1 == m || col + 1 == n)
            break;
            
        prev = mat[row + 1][col];
        
        for (int i = col; i < n; i++)
        {
            curr = mat[row][i];
            mat[row][i] = prev;
            prev = curr;
        }
        row++;
        
        for (int i = row; i < m; i++)
        {
            curr = mat[i][n-1];
            mat[i][n-1] = prev;
            prev = curr;
        }
        n--;
        
        if (row < m)
        {
            for (int i = n-1; i >= col; i--)
            {
                curr = mat[m-1][i];
                mat[m-1][i] = prev;
                prev = curr;
            }
        }
        m--;
        
        if (col < n)
        {
            for (int i = m-1; i >= row; i--)
            {
                curr = mat[i][col];
                mat[i][col] = prev;
                prev = curr;
            }
        }
        col++;
    }
    
    for (int i=0; i<R; i++)
    {
        for (int j=0; j<C; j++)
            cout << mat[i][j] << " ";
        cout << endl;
    }
}

int main()
{
    int a[R][C] = { {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16} };
    
    rotatematrix(R, C, a);
    return 0;
}

2. 程序Python版

def rotateMatrix(mat): 

	if not len(mat): 
		return
	
	top = 0
	bottom = len(mat)-1

	left = 0
	right = len(mat[0])-1

	while left < right and top < bottom: 
 
		prev = mat[top+1][left] 

		for i in range(left, right+1): 
			curr = mat[top][i] 
			mat[top][i] = prev 
			prev = curr 

		top += 1

		for i in range(top, bottom+1): 
			curr = mat[i][right] 
			mat[i][right] = prev 
			prev = curr 

		right -= 1

		for i in range(right, left-1, -1): 
			curr = mat[bottom][i] 
			mat[bottom][i] = prev 
			prev = curr 

		bottom -= 1

		for i in range(bottom, top-1, -1): 
			curr = mat[i][left] 
			mat[i][left] = prev 
			prev = curr 

		left += 1

	return mat 

def printMatrix(mat): 
	for row in mat: 
		print row 
		
matrix =[ 
			[1, 2, 3, 4 ], 
			[5, 6, 7, 8 ], 
			[9, 10, 11, 12 ], 
			[13, 14, 15, 16 ] 
		] 
matrix = rotateMatrix(matrix) 
printMatrix(matrix)