全国高校绿色计算大赛 预赛第一阶段(C++)第3关:旋转数组

挑战任务

在计算机中,一张数字图像,可以被看做是一个矩阵或者说数组。

学过线性代数的同学对矩阵肯定不陌生。一般来说,图像是一个标准的矩形,有着宽度(width)和高度(height)。而矩阵有着行(row)和列(column),矩阵的操作在数学和计算机中的处理都很常见且成熟,于是很自然的就把图像作为一个矩阵,把对图像的操作转换成对矩阵的操作,实际上所有的图像处理工具都是这么做的。

所以我们如果要对图像进行操作,其实也就是在对一个数组进行操作。

本关要求你编写代码实现对一张图像的90°旋转,即对矩阵的90°旋转。

编程要求

补全函数void rotate(vector<vector<int> >& matrix),实现对输入的数组进行旋转的功能。

注意:

你必须使用原地算法来旋转图像,而不能重新创建一个数组,本关不需要你输出数组,只需要修改数组metrix即可。

测试说明

输入:
3 3

1 2 3
4 5 6
7 8 9

原地旋转,使其变为:

7 4 1
8 5 2
9 6 3

输入的3 3是用作构建数组的不会作为函数的参数输入,可以忽略。

#ifndef _TEST
#define _TEST
#include <iostream>
#include <vector>
using namespace std;

class Task{
	public:
		void rotate(vector<vector<int> >& matrix){
        /********* Begin *********/
		 int length = matrix.size();  

	     for (int i = 0; i < length; i++) {
	         for (int j = 0; j < length - i; j++) {
	             int tmp = matrix[i][j];
	             matrix[i][j] = matrix[length - j - 1][length - i - 1];
	             matrix[length - j - 1][length - i - 1] = tmp;
	         }
	     }
           
	     for (int i = 0; i < length; i++) {
	         for (int j = 0; j < length / 2; j++) {
	             int tmp = matrix[j][i];
	             matrix[j][i] = matrix[length - j - 1][i];
	             matrix[length - j - 1][i] = tmp;
	         }
	     }            
		 
        /********* End *********/	        
			
			}
};
#endif

  

#ifndef _TEST
#define _TEST
#include <iostream>
#include <vector>
using namespace std;

class Task{
	public:
		vector<char> inversion(string str){
            vector <char> vec;
            int index = str.length();
            while(index--){
            	vec.push_back(str[index]);
            	}	
            return vec;
			}
};
#endif

  

#include <iostream>
#include <vector>
#include <stdio.h>
#include "Task.hpp"

using namespace std;


int main(){
	string str;
	getline(cin,str);

	Task tt;
    vector <char> result;
	result = tt.inversion(str);
    for(int i = 0; i<str.length();i++){
    	cout << result[i];   
    }
    cout << endl;
}

  

运行结果

原文地址:https://www.cnblogs.com/277223178dudu/p/9869728.html